org.apache.commons.lang3.tuple.ImmutableTriple Java Examples

The following examples show how to use org.apache.commons.lang3.tuple.ImmutableTriple. 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: RandomValueGenerator.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public ImmutableTriple<Country, Country, Country> generateTeamTriple() {
	Set<Country> countries = countryService.getAvailableCountriesWithoutNoneEntry();
	List<Country> availCountries = new ArrayList<Country>(countries);
	if (CollectionUtils.isEmpty(availCountries)) {
		return null;
	}

	Country countryOne = generateRandomCountry(availCountries);
	availCountries.remove(countryOne);

	if (CollectionUtils.isEmpty(availCountries)) {
		return ImmutableTriple.of(countryOne, countryOne, countryOne);
	}

	Country countryTwo = generateRandomCountry(availCountries);
	availCountries.remove(countryTwo);

	if (CollectionUtils.isEmpty(availCountries)) {
		return ImmutableTriple.of(countryOne, countryTwo, countryTwo);
	}

	Country countryThree = generateRandomCountry(availCountries);

	return ImmutableTriple.of(countryOne, countryTwo, countryThree);
}
 
Example #2
Source File: Router.java    From httpkit with Apache License 2.0 6 votes vote down vote up
private ImmutableTriple<String, String, String> findResourcePathFromFreemarkerRouteMap(String uri)
{
    //2.查找不到,则从docRoutesMap中查找  例如
    //uri:       /root/web/page/index.ftl
    //key:       /root/web
    //value:     static/
    for (String key : freemarkerRoutesMap.keySet())
    {
        if (uri.startsWith(key + "/"))
        {
            //uri:       /root/web/page/index.ftl
            //key:       /root/web
            //value:     static/
            
            //key:       /root/web/
            String subPath = StringUtils.removeStart(uri, key + "/");
            //subPath:   page/index.ftl
            //uri解码,即可完美支持中文
            subPath = URIEncoderDecoder.decode(subPath);
            return new ImmutableTriple<String, String, String>(key + "/", freemarkerRoutesMap.get(key), subPath);
        }
    }
    return null;
}
 
Example #3
Source File: PrimitiveCollectionInvocationHandler.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Triple<List<T>, URI, List<ClientAnnotation>> fetchPartial(final URI uri, final Class<T> typeRef) {
  final ODataPropertyRequest<ClientProperty> req =
          getClient().getRetrieveRequestFactory().getPropertyRequest(uri);
    req.setPrefer(getClient().newPreferences().includeAnnotations("*"));

  final ODataRetrieveResponse<ClientProperty> res = req.execute();

  final List<T> resItems = new ArrayList<T>();

  final ClientProperty property = res.getBody();
  if (property != null && !property.hasNullValue()) {
    for (ClientValue item : property.getCollectionValue()) {
      resItems.add((T) item.asPrimitive().toValue());
    }
  }

  return new ImmutableTriple<List<T>, URI, List<ClientAnnotation>>(
          resItems, null, Collections.<ClientAnnotation>emptyList());
}
 
Example #4
Source File: FSSorter.java    From twister2 with Apache License 2.0 6 votes vote down vote up
private void init(List<Tuple> inMemoryValues) {
  // lets open the files
  for (int i = 0; i < noOfFiles; i++) {
    String fileName = folder + "/part_" + i;
    Triple<List<Tuple>, Long, Long> fileParts = FileLoader.openFilePart(fileName,
        0, openBytes, keyType, dataType, deserializer);
    openList.add(new FilePart(fileParts));
  }
  // add the in-memory values to the last
  openList.add(new FilePart(new ImmutableTriple<>(inMemoryValues, 0L, 0L)));

  // lets add to the heap the first element
  for (int i = 0; i < openList.size(); i++) {
    FilePart p = openList.get(i);
    List<Tuple> list = p.keyValues.getLeft();
    if (list.size() > p.currentIndex) {
      heap.insert(list.get(p.currentIndex), i);
      p.currentIndex++;
    }
  }
}
 
Example #5
Source File: GrpcHystrixCommand.java    From saluki with Apache License 2.0 6 votes vote down vote up
public GrpcHystrixCommand(String serviceName, String methodName, Boolean isEnabledFallBack) {
  super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(serviceName))//
      .andCommandKey(HystrixCommandKey.Factory.asKey(serviceName + ":" + methodName))//
      .andCommandPropertiesDefaults(
          HystrixCommandProperties.Setter().withCircuitBreakerRequestVolumeThreshold(20)// 10秒钟内至少19此请求失败,熔断器才发挥起作用
              .withCircuitBreakerSleepWindowInMilliseconds(30000)// 熔断器中断请求30秒后会进入半打开状态,放部分流量过去重试
              .withCircuitBreakerErrorThresholdPercentage(50)// 错误率达到50开启熔断保护
              .withExecutionTimeoutEnabled(false)// 禁用这里的超时
              .withFallbackEnabled(isEnabledFallBack))//
      .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(100)
          .withAllowMaximumSizeToDivergeFromCoreSize(true).withMaximumSize(Integer.MAX_VALUE)));
  this.serviceName = serviceName;
  this.methodName = methodName;
  this.start = System.currentTimeMillis();
  this.rpcContext = new ImmutableTriple<Map<String, String>, Map<String, Object>, Set<Class>>(
      RpcContext.getContext().getAttachments(), RpcContext.getContext().get(),
      RpcContext.getContext().getHoldenGroups());
  RpcContext.removeContext();
}
 
Example #6
Source File: DruidRules.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Given a list of conditions that contain Druid valid operations and
 * a list that contains those that contain any non-supported operation,
 * it outputs a triple with three different categories:
 * 1-l) condition filters on the timestamp column,
 * 2-m) condition filters that can be pushed to Druid,
 * 3-r) condition filters that cannot be pushed to Druid.
 */
private static Triple<List<RexNode>, List<RexNode>, List<RexNode>> splitFilters(
    final RexBuilder rexBuilder, final DruidQuery input, final List<RexNode> validPreds,
    final List<RexNode> nonValidPreds, final int timestampFieldIdx) {
  final List<RexNode> timeRangeNodes = new ArrayList<>();
  final List<RexNode> pushableNodes = new ArrayList<>();
  final List<RexNode> nonPushableNodes = new ArrayList<>(nonValidPreds);
  // Number of columns with the dimensions and timestamp
  for (RexNode conj : validPreds) {
    final RelOptUtil.InputReferencedVisitor visitor = new RelOptUtil.InputReferencedVisitor();
    conj.accept(visitor);
    if (visitor.inputPosReferenced.contains(timestampFieldIdx)
        && visitor.inputPosReferenced.size() == 1) {
      timeRangeNodes.add(conj);
    } else {
      pushableNodes.add(conj);
    }
  }
  return ImmutableTriple.of(timeRangeNodes, pushableNodes, nonPushableNodes);
}
 
Example #7
Source File: MultipleReturnValuesUsingApacheCommonsTripleUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
void whenUsingTriple_thenMultipleFieldsAreReturned() {

    List<Coordinates> coordinatesList = new ArrayList<>();
    coordinatesList.add(new Coordinates(1, 1, "home"));
    coordinatesList.add(new Coordinates(2, 2, "school"));
    coordinatesList.add(new Coordinates(3, 3, "hotel"));

    Coordinates target = new Coordinates(5, 5, "gym");

    ImmutableTriple<Double, Double, Double> minAvgMax = MultipleReturnValuesUsingApacheCommonsTriple.getMinAvgMaxTriple(coordinatesList, target);

    assertEquals(2.83, scaleDouble(minAvgMax.left));   //min
    assertEquals(4.24, scaleDouble(minAvgMax.middle)); //avg
    assertEquals(5.66, scaleDouble(minAvgMax.right));  //max
}
 
Example #8
Source File: RandomValueGeneratorIT.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Test
public void generateTeamTriple() {
    dataBasePopulator.createRandomMatches();

    for (int i = 0; i < 100; i++) {
        ImmutableTriple<Country, Country, Country> triple = randomValueGenerator.generateTeamTriple();
        assertThat(triple).isNotNull();
        Country countryOne = triple.getLeft();
        Country countryTwo = triple.getMiddle();
        Country countryThree = triple.getRight();
        assertThat(countryOne).isNotNull();
        assertThat(countryTwo).isNotNull();
        assertThat(countryThree).isNotNull();

        assertThat(countryOne).isNotEqualTo(countryTwo);
        assertThat(countryTwo).isNotEqualTo(countryThree);
        assertThat(countryThree).isNotEqualTo(countryOne);

        assertThat(Country.NONE).isNotEqualTo(countryOne);
        assertThat(Country.NONE).isNotEqualTo(countryTwo);
        assertThat(Country.NONE).isNotEqualTo(countryThree);
    }
}
 
Example #9
Source File: PlaceDAOImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public Stream<Triple<UUID, UUID, ServiceLevel>> streamPlaceAndAccountAndServiceLevelByPartitionId(int partitionId) {
  	try(Context ctxt = streamPlaceAndAccountAndServiceLevelByPartitionIdTimer.time()) {
        BoundStatement bs = streamPlaceAndAccountAndServiceLevelByPartitionId.bind(partitionId);
        //bs.setConsistencyLevel(ConsistencyLevel.LOCAL_ONE);
        ResultSet rs = session.execute(bs);
        return stream(rs, (row) -> {
        	ServiceLevel s = ServiceLevel.BASIC;
        	String fromDb = row.getString(PlaceEntityColumns.SERVICE_LEVEL);
        	if(StringUtils.isNotBlank(fromDb)) {
        		s = ServiceLevel.valueOf(fromDb);
        	}
           return new ImmutableTriple<>(row.getUUID(BaseEntityColumns.ID), row.getUUID(PlaceEntityColumns.ACCOUNT_ID), s);
        });
     }
}
 
Example #10
Source File: LineRegexReplaceInRegionBolt.java    From cognition with Apache License 2.0 6 votes vote down vote up
void configureRegexRegions(Configuration conf) throws ConfigurationException {
  List<String> regexRegionGroupList = conf.getList(REGEX_REGION_GROUP).stream().map(o -> o.toString()).collect(Collectors.toList());
  List<String> regexRegionSearchList = conf.getList(REGEX_REGION_SEARCH).stream().map(o -> o.toString()).collect(Collectors.toList());
  List<String> regexRegionReplaceList = conf.getList(REGEX_REGION_REPLACE).stream().map(o -> o.toString()).collect(Collectors.toList());

  int groupListSize = regexRegionGroupList.size();
  int searchListSize = regexRegionSearchList.size();
  int replaceListSize = regexRegionReplaceList.size();
  if (!(groupListSize == searchListSize && searchListSize == replaceListSize)) {
    // all lists must be the same size
    throw new ConfigurationException("Error initializing class. All regexRegion lists must be the same size");
  }

  groupSearchReplaceList = new ArrayList<>(groupListSize);
  for (int index = 0; index < regexRegionGroupList.size(); index++) {
    Pattern pattern = Pattern.compile(regexRegionGroupList.get(index));
    String regex = regexRegionSearchList.get(index);
    String replacement = regexRegionReplaceList.get(index);

    ImmutableTriple<Pattern, String, String> triple = new ImmutableTriple<>(pattern, regex, replacement);
    groupSearchReplaceList.add(triple);
  }
}
 
Example #11
Source File: DruidRules.java    From Quicksql with MIT License 6 votes vote down vote up
public void onMatch(RelOptRuleCall call) {
  final Aggregate aggregate = call.rel(0);
  final DruidQuery query = call.rel(1);
  if (!DruidQuery.isValidSignature(query.signature() + 'a')) {
    return;
  }

  if (aggregate.indicator
          || aggregate.getGroupSets().size() != 1
          || BAD_AGG.apply(ImmutableTriple.of(aggregate, (RelNode) aggregate, query))
          || !validAggregate(aggregate, query)) {
    return;
  }
  final RelNode newAggregate = aggregate.copy(aggregate.getTraitSet(),
          ImmutableList.of(Util.last(query.rels)));
  call.transformTo(DruidQuery.extendQuery(query, newAggregate));
}
 
Example #12
Source File: DruidRules.java    From Quicksql with MIT License 6 votes vote down vote up
/**
 * Given a list of conditions that contain Druid valid operations and
 * a list that contains those that contain any non-supported operation,
 * it outputs a triple with three different categories:
 * 1-l) condition filters on the timestamp column,
 * 2-m) condition filters that can be pushed to Druid,
 * 3-r) condition filters that cannot be pushed to Druid.
 */
private static Triple<List<RexNode>, List<RexNode>, List<RexNode>> splitFilters(
        final RexBuilder rexBuilder, final DruidQuery input, final List<RexNode> validPreds,
        final List<RexNode> nonValidPreds, final int timestampFieldIdx) {
  final List<RexNode> timeRangeNodes = new ArrayList<>();
  final List<RexNode> pushableNodes = new ArrayList<>();
  final List<RexNode> nonPushableNodes = new ArrayList<>(nonValidPreds);
  // Number of columns with the dimensions and timestamp
  for (RexNode conj : validPreds) {
    final RelOptUtil.InputReferencedVisitor visitor = new RelOptUtil.InputReferencedVisitor();
    conj.accept(visitor);
    if (visitor.inputPosReferenced.contains(timestampFieldIdx)) {
      if (visitor.inputPosReferenced.size() != 1) {
        // Complex predicate, transformation currently not supported
        nonPushableNodes.add(conj);
      } else {
        timeRangeNodes.add(conj);
      }
    } else {
      pushableNodes.add(conj);
    }
  }
  return ImmutableTriple.of(timeRangeNodes, pushableNodes, nonPushableNodes);
}
 
Example #13
Source File: ComplexCollectionInvocationHandler.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Triple<List<T>, URI, List<ClientAnnotation>> fetchPartial(final URI uri, final Class<T> typeRef) {
  final ODataPropertyRequest<ClientProperty> req =
      getClient().getRetrieveRequestFactory().getPropertyRequest(uri);
  req.setPrefer(getClient().newPreferences().includeAnnotations("*"));

  final ODataRetrieveResponse<ClientProperty> res = req.execute();

  final List<T> resItems = new ArrayList<T>();

  final ClientProperty property = res.getBody();
  if (property != null && property.hasCollectionValue()) {
    for (ClientValue item : (ClientCollectionValue<ClientValue>) property.getValue()) {
      Class<?> actualRef = null;
      if (StringUtils.isNotBlank(item.getTypeName())) {
        actualRef = service.getComplexTypeClass(item.getTypeName());
      }
      if (actualRef == null) {
        actualRef = typeRef;
      }

      resItems.add((T) getComplex(property.getName(), item, actualRef, null, null, true));
    }
  }

  return new ImmutableTriple<List<T>, URI, List<ClientAnnotation>>(
      resItems, null, Collections.<ClientAnnotation> emptyList());
}
 
Example #14
Source File: GitHubRepo.java    From HubTurbo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public ImmutableTriple<List<TurboIssue>, String, Date> getUpdatedIssues(String repoId,
                                                                        String eTag, Date lastCheckTime) {

    IssueUpdateService issueUpdateService = new IssueUpdateService(client, eTag, lastCheckTime);
    List<Issue> updatedItems = issueUpdateService.getUpdatedItems(RepositoryId.createFromId(repoId));
    List<TurboIssue> items = updatedItems.stream()
            .map(i -> new TurboIssue(repoId, i))
            .collect(Collectors.toList());
    return new ImmutableTriple<>(items, issueUpdateService.getUpdatedETags(),
                                 issueUpdateService.getUpdatedCheckTime());
}
 
Example #15
Source File: DownloadIssuesUpdatesTask.java    From HubTurbo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
    ImmutableTriple<List<TurboIssue>, String, Date> changes = repo.getUpdatedIssues(model.getRepoId(),
                                                                                    model.getUpdateSignature()
                                                                                            .issuesETag, model
                                                                                            .getUpdateSignature()
                                                                                            .lastCheckTime);
    List<TurboIssue> updatedIssues = changes.left;
    logger.info(HTLog.format(model.getRepoId(), "%s issue(s)) changed%s",
                             updatedIssues.size(), updatedIssues.isEmpty() ? "" : ": " + updatedIssues));
    response.complete(new Result<>(updatedIssues, changes.middle, changes.right));
}
 
Example #16
Source File: DummyRepoState.java    From HubTurbo with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected ImmutableTriple<List<TurboIssue>, String, Date> getUpdatedIssues(String eTag, Date lastCheckTime) {

        String currETag = eTag;
        if (!updatedIssues.isEmpty() || eTag == null) currETag = UUID.randomUUID().toString();

        ImmutableTriple<List<TurboIssue>, String, Date> toReturn = new ImmutableTriple<>(
                deepCopyIssues(updatedIssues), currETag, lastCheckTime);

        updatedIssues = new TreeMap<>();
        return toReturn;
    }
 
Example #17
Source File: FileUtil.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
private static List<DocumentFile> convertFromUris(@NonNull final Context context, @NonNull final List<ImmutableTriple<Uri, String, Long>> uris) {
    final List<DocumentFile> resultFiles = new ArrayList<>();
    for (ImmutableTriple<Uri, String, Long> uri : uris) {
        DocumentFile docFile = fromTreeUriCached(context, uri.left);
        // Following line should be the proper way to go but it's inefficient as it calls queryIntentContentProviders from scratch repeatedly
        //DocumentFile docFile = DocumentFile.fromTreeUri(context, uri.left);
        if (docFile != null)
            resultFiles.add(new CachedDocumentFile(docFile, uri.middle, uri.right));
    }
    return resultFiles;
}
 
Example #18
Source File: MultipleReturnValuesUsingApacheCommonsTriple.java    From tutorials with MIT License 5 votes vote down vote up
static ImmutableTriple<Double, Double, Double> getMinAvgMaxTriple(
  List<Coordinates> coordinatesList,
  Coordinates target) {

    List<Double> distanceList = coordinatesList.stream()
      .map(coordinates -> coordinates.calculateDistance(target))
      .collect(Collectors.toList());
    Double minDistance = distanceList.stream().mapToDouble(Double::doubleValue).min().getAsDouble();
    Double avgDistance = distanceList.stream().mapToDouble(Double::doubleValue).average().orElse(0.0D);
    Double maxDistance = distanceList.stream().mapToDouble(Double::doubleValue).max().getAsDouble();

    return ImmutableTriple.of(minDistance, avgDistance, maxDistance);
}
 
Example #19
Source File: ArangoDBConfigurationBuilder.java    From arangodb-tinkerpop-provider with Apache License 2.0 5 votes vote down vote up
/**
 * Configure a 1-to-1 edge, i.e. for a given edge collection define the source and target vertex
 * collections.
 *
 * @param edgeCollection 		the edge collection
 * @param sourceCollection 		the source vertex collection
 * @param targetCollection 		the target vertex collection
 * @return a reference to this object.
 */

public ArangoDBConfigurationBuilder configureEdge(
	String edgeCollection,
	String sourceCollection,
	String targetCollection) {
	Set<String> source = new HashSet<>();
	Set<String> target = new HashSet<>();
	source.add(sourceCollection);
	target.add(targetCollection);
	ImmutableTriple<String, Set<String>, Set<String>> triple = new ImmutableTriple<>(edgeCollection, source, target);
	relations.add(triple);
	return this;
}
 
Example #20
Source File: ArangoDBConfigurationBuilder.java    From arangodb-tinkerpop-provider with Apache License 2.0 5 votes vote down vote up
/**
 * Configure a 1-to-many edge, i.e. for a given edge collection define the source and target vertex
 * collections.
 *
 * @param edgeCollection 		the edge collection
 * @param sourceCollection 		the source vertex collection
 * @param targetCollections 	the target vertices collections
 * @return a reference to this object.
 */

public ArangoDBConfigurationBuilder configureEdge(
	String edgeCollection,
	String sourceCollection,
	Set<String> targetCollections) {
	Set<String> source = new HashSet<>();
	source.add(sourceCollection);
	ImmutableTriple<String, Set<String>, Set<String>> triple = new ImmutableTriple<>(edgeCollection, source, Collections.unmodifiableSet(targetCollections));
	relations.add(triple);
	return this;
}
 
Example #21
Source File: ArangoDBConfigurationBuilder.java    From arangodb-tinkerpop-provider with Apache License 2.0 5 votes vote down vote up
/**
 * Configure a many-to-1 edge, i.e. for a given edge collection define the source and target vertex
 * collections.
 *
 * @param edgeCollection 		the edge collection
 * @param sourceCollections 	the source vertices collections
 * @param targetCollection 		the target vertex collection
 * @return a reference to this object.
 */

public ArangoDBConfigurationBuilder configureEdge(
	String edgeCollection,
	Set<String> sourceCollections,
	String targetCollection) {
	Set<String> target = new HashSet<>();
	target.add(targetCollection);
	ImmutableTriple<String, Set<String>, Set<String>> triple = new ImmutableTriple<>(edgeCollection, Collections.unmodifiableSet(sourceCollections), target);
	relations.add(triple);
	return this;
}
 
Example #22
Source File: ArangoDBConfigurationBuilder.java    From arangodb-tinkerpop-provider with Apache License 2.0 5 votes vote down vote up
/**
 * Configure a many-to-many edge, i.e. for a given edge collection define the source and target vertex
 * collections.
 *
 * @param edgeCollection 		the edge collection
 * @param sourceCollections 	the source vertices collections
 * @param targetCollections 	the target vertices collections
 * @return a reference to this object.
 */

public ArangoDBConfigurationBuilder configureEdge(
	String edgeCollection,
	Set<String> sourceCollections,
	Set<String> targetCollections) {
	ImmutableTriple<String, Set<String>, Set<String>> triple = new ImmutableTriple<>(edgeCollection, Collections.unmodifiableSet(sourceCollections), Collections.unmodifiableSet(targetCollections));
	relations.add(triple);
	return this;
}
 
Example #23
Source File: AbstractPOJOGenMojo.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private Triple<XMLMetadata, String, Edm> getMetadata() throws FileNotFoundException {
  if (StringUtils.isEmpty(serviceRootURL) && StringUtils.isEmpty(localEdm)) {
    throw new IllegalArgumentException("Must provide either serviceRootURL or localEdm");
  }
  if (StringUtils.isNotEmpty(serviceRootURL) && StringUtils.isNotEmpty(localEdm)) {
    throw new IllegalArgumentException("Must provide either serviceRootURL or localEdm, not both");
  }

  XMLMetadata metadata = null;
  String metadataETag = null;
  Edm edm = null;
  if (StringUtils.isNotEmpty(serviceRootURL)) {
    final EdmMetadataRequest req = getClient().getRetrieveRequestFactory().getMetadataRequest(serviceRootURL);
    metadata = req.getXMLMetadata();
    final ODataRetrieveResponse<Edm> res = req.execute();
    metadataETag = res.getETag();
    edm = res.getBody();
  } else if (StringUtils.isNotEmpty(localEdm)) {
    final FileInputStream fis = new FileInputStream(FileUtils.getFile(localEdm));
    try {
      metadata = getClient().getDeserializer(ContentType.APPLICATION_XML).toMetadata(fis);
      edm = getClient().getReader().readMetadata(metadata.getSchemaByNsOrAlias());
    } finally {
      IOUtils.closeQuietly(fis);
    }
  }

  if (metadata == null || edm == null) {
    throw new IllegalStateException("Metadata not found");
  }
  return new ImmutableTriple<XMLMetadata, String, Edm>(metadata, metadataETag, edm);
}
 
Example #24
Source File: FileUtil.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
static List<DocumentFile> listDocumentFiles(
        @NonNull final Context context,
        @NonNull final DocumentFile parent,
        @NonNull final ContentProviderClient client,
        final FileHelper.NameFilter nameFilter,
        boolean listFolders,
        boolean listFiles) {
    final List<ImmutableTriple<Uri, String, Long>> results = new ArrayList<>();

    final Uri searchUri = DocumentsContract.buildChildDocumentsUriUsingTree(parent.getUri(), DocumentsContract.getDocumentId(parent.getUri()));
    try (Cursor c = client.query(searchUri, new String[]{
            DocumentsContract.Document.COLUMN_DOCUMENT_ID,
            DocumentsContract.Document.COLUMN_DISPLAY_NAME,
            DocumentsContract.Document.COLUMN_MIME_TYPE,
            DocumentsContract.Document.COLUMN_SIZE}, null, null, null)) {
        if (c != null)
            while (c.moveToNext()) {
                final String documentId = c.getString(0);
                final String documentName = c.getString(1);
                boolean isFolder = c.getString(2).equals(DocumentsContract.Document.MIME_TYPE_DIR);
                final Long documentSize = c.getLong(3);

                // FileProvider doesn't take query selection arguments into account, so the selection has to be done manually
                if ((null == nameFilter || nameFilter.accept(documentName)) && ((listFiles && !isFolder) || (listFolders && isFolder)))
                    results.add(new ImmutableTriple<>(DocumentsContract.buildDocumentUriUsingTree(parent.getUri(), documentId), documentName, documentSize));
            }
    } catch (Exception e) {
        Timber.w(e, "Failed query");
    }

    return convertFromUris(context, results);
}
 
Example #25
Source File: ExportKeysTest.java    From hbase-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegexAll() throws Exception {
    if (miniCluster) {
        String outputFile = "exportkeys_test.keys";

        try {
            String splitPoint = "splitpoint";
            splitTable(splitPoint.getBytes());
            String tableName2 = createAdditionalTable(tableName + "2");
            splitTable(tableName2, splitPoint.getBytes());

            String[] argsParam = {"zookeeper", ".*", outputFile};
            Args args = new ManagerArgs(argsParam);
            assertEquals("zookeeper", args.getZookeeperQuorum());
            ExportKeys command = new ExportKeys(admin, args);

            waitForSplitting(2);
            waitForSplitting(tableName2, 2);
            command.run();

            List<Triple<String, String, String>> results = new ArrayList<>();
            for (String keys : Files.readAllLines(Paths.get(outputFile), Constant.CHARSET)) {

                String[] split = keys.split(ExportKeys.DELIMITER);
                results.add(new ImmutableTriple<>(split[0], split[1], split[2]));
            }
            assertEquals(4, results.size());
        } finally {
            Files.delete(Paths.get(outputFile));
        }
    }
}
 
Example #26
Source File: ExportKeysTest.java    From hbase-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegex() throws Exception {
    String outputFile = "exportkeys_test.keys";

    try {
        String splitPoint = "splitpoint";
        splitTable(splitPoint.getBytes());
        String tableName2 = createAdditionalTable(tableName + "2");
        splitTable(tableName2, splitPoint.getBytes());

        String tableNameRegex = tableName + ".*";
        String[] argsParam = {"zookeeper", tableNameRegex, outputFile};
        Args args = new ManagerArgs(argsParam);
        assertEquals("zookeeper", args.getZookeeperQuorum());
        ExportKeys command = new ExportKeys(admin, args);

        waitForSplitting(2);
        waitForSplitting(tableName2, 2);
        command.run();

        List<Triple<String, String, String>> results = new ArrayList<>();
        for (String keys : Files.readAllLines(Paths.get(outputFile), Constant.CHARSET)) {

            String[] split = keys.split(ExportKeys.DELIMITER);
            results.add(new ImmutableTriple<>(split[0], split[1], split[2]));
        }
        assertEquals(4, results.size());
    } finally {
        Files.delete(Paths.get(outputFile));
    }
}
 
Example #27
Source File: ExportKeysTest.java    From hbase-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testRunOptimize() throws Exception {
    String outputFile = "exportkeys_test.keys";

    try {
        String splitPoint = "splitpoint";

        splitTable(splitPoint.getBytes());

        String[] argsParam = {"zookeeper", tableName, outputFile, "--optimize=1g"};
        Args args = new ManagerArgs(argsParam);
        assertEquals("zookeeper", args.getZookeeperQuorum());
        ExportKeys command = new ExportKeys(admin, args);

        waitForSplitting(2);
        command.run();

        List<Triple<String, String, String>> results = new ArrayList<>();
        for (String keys : Files.readAllLines(Paths.get(outputFile), Constant.CHARSET)) {

            String[] split = keys.split(ExportKeys.DELIMITER);
            results.add(new ImmutableTriple<>(split[0], split[1], split[2]));
        }
        assertEquals(0, results.size());
    } finally {
        Files.delete(Paths.get(outputFile));
    }
}
 
Example #28
Source File: ExportKeysTest.java    From hbase-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegexAll() throws Exception {
    if (miniCluster) {
        String outputFile = "exportkeys_test.keys";

        try {
            String splitPoint = "splitpoint";
            splitTable(splitPoint.getBytes());
            String tableName2 = createAdditionalTable(tableName + "2");
            splitTable(tableName2, splitPoint.getBytes());

            String[] argsParam = {"zookeeper", ".*", outputFile};
            Args args = new ManagerArgs(argsParam);
            assertEquals("zookeeper", args.getZookeeperQuorum());
            ExportKeys command = new ExportKeys(admin, args);

            waitForSplitting(2);
            waitForSplitting(tableName2, 2);
            command.run();

            List<Triple<String, String, String>> results = new ArrayList<>();
            for (String keys : Files.readAllLines(Paths.get(outputFile), Constant.CHARSET)) {

                String[] split = keys.split(ExportKeys.DELIMITER);
                results.add(new ImmutableTriple<>(split[0], split[1], split[2]));
            }
            assertEquals(4, results.size());
        } finally {
            Files.delete(Paths.get(outputFile));
        }
    }
}
 
Example #29
Source File: ExportKeysTest.java    From hbase-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegex() throws Exception {
    String outputFile = "exportkeys_test.keys";

    try {
        String splitPoint = "splitpoint";
        splitTable(splitPoint.getBytes());
        String tableName2 = createAdditionalTable(tableName + "2");
        splitTable(tableName2, splitPoint.getBytes());

        String tableNameRegex = tableName + ".*";
        String[] argsParam = {"zookeeper", tableNameRegex, outputFile};
        Args args = new ManagerArgs(argsParam);
        assertEquals("zookeeper", args.getZookeeperQuorum());
        ExportKeys command = new ExportKeys(admin, args);

        waitForSplitting(2);
        waitForSplitting(tableName2, 2);
        command.run();

        List<Triple<String, String, String>> results = new ArrayList<>();
        for (String keys : Files.readAllLines(Paths.get(outputFile), Constant.CHARSET)) {

            String[] split = keys.split(ExportKeys.DELIMITER);
            results.add(new ImmutableTriple<>(split[0], split[1], split[2]));
        }
        assertEquals(4, results.size());
    } finally {
        Files.delete(Paths.get(outputFile));
    }
}
 
Example #30
Source File: RandomValueGeneratorUT.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Test
public void generateTripleButOnlyOneCountryAvailable() {
    when(countryService.getAvailableCountriesWithoutNoneEntry()).thenReturn(new HashSet<>(Collections.singletonList(Country.RUSSIA)));

    ImmutableTriple<Country, Country, Country> triple = randomValueGenerator.generateTeamTriple();
    assertThat(triple).isNotNull();
}