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

The following examples show how to use org.apache.commons.lang3.tuple.ImmutablePair. 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: Cardinality.java    From angelix with MIT License 6 votes vote down vote up
private static Pair<List<Node>, List<? extends Variable>> makeSortingNetwork(List<? extends Variable> bits) {
    int n = bits.size();
    if (n == 1) {
        return new ImmutablePair<>(new ArrayList<>(), bits);
    }
    if (n == 2) {
        return twoComp(bits.get(0), bits.get(1));
    }
    List<Node> algorithm = new ArrayList<>();
    List<Variable> sorted = new ArrayList<>();

    int l = n/2;
    List<? extends Variable> left = bits.subList(0, l);
    List<? extends Variable> right = bits.subList(l, n);
    Pair<List<Node>, List<? extends Variable>> leftNetwork = makeSortingNetwork(left);
    Pair<List<Node>, List<? extends Variable>> rightNetwork = makeSortingNetwork(right);
    algorithm.addAll(leftNetwork.getLeft());
    algorithm.addAll(rightNetwork.getLeft());
    Pair<List<Node>, List<? extends Variable>> mergeResult = merge(leftNetwork.getRight(), rightNetwork.getRight());
    algorithm.addAll(mergeResult.getLeft());
    sorted.addAll(mergeResult.getRight());

    return new ImmutablePair<>(algorithm, sorted);
}
 
Example #2
Source File: UpdateService.java    From HubTurbo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Gets a list of ETags for all pages returned from an API request and
 * also return the connection used to get the ETags so that their last check time
 * can be recorded elsewhere
 *
 * @param request
 * @param client
 * @return a Optional list of ETags for all pages returned from an API request and
 * corresponding HTTP connection or an empty Optional if an error occurs
 */
private Optional<ImmutablePair<List<String>, HttpURLConnection>> getPagedEtags(
        GitHubRequest request, GitHubClientEx client) {

    PageHeaderIterator iter = new PageHeaderIterator(request, client, "ETag");
    List<String> etags = new ArrayList<>();
    HttpURLConnection connection = null;

    while (iter.hasNext()) {
        try {
            etags.add(Utility.stripQuotes(iter.next()));
            if (connection == null) {
                connection = iter.getLastConnection();
            }
        } catch (NoSuchPageException e) {
            logger.error("No such page exception at " + iter.getRequest().generateUri());
            return Optional.empty();
        }
    }

    return Optional.of(new ImmutablePair<>(etags, connection));
}
 
Example #3
Source File: EdgeLabel.java    From sqlg with MIT License 6 votes vote down vote up
public void ensurePropertiesExist(Map<String, PropertyType> columns) {
    for (Map.Entry<String, PropertyType> column : columns.entrySet()) {
        if (!this.properties.containsKey(column.getKey())) {
            Preconditions.checkState(!this.getSchema().isSqlgSchema(), "schema may not be %s", SQLG_SCHEMA);
            this.sqlgGraph.getSqlDialect().validateColumnName(column.getKey());
            if (!this.uncommittedProperties.containsKey(column.getKey())) {
                this.getSchema().getTopology().lock();
                if (!getProperty(column.getKey()).isPresent()) {
                    TopologyManager.addEdgeColumn(this.sqlgGraph, this.getSchema().getName(), EDGE_PREFIX + getLabel(), column, new ListOrderedSet<>());
                    addColumn(this.getSchema().getName(), EDGE_PREFIX + getLabel(), ImmutablePair.of(column.getKey(), column.getValue()));
                    PropertyColumn propertyColumn = new PropertyColumn(this, column.getKey(), column.getValue());
                    propertyColumn.setCommitted(false);
                    this.uncommittedProperties.put(column.getKey(), propertyColumn);
                    this.getSchema().getTopology().fire(propertyColumn, "", TopologyChangeAction.CREATE);
                }
            }
        }
    }
}
 
Example #4
Source File: WithBlockTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
protected Pair<DisjointPattern, Constructor> findConstructor(String table, String firstPrint) {
	AtomicReference<DisjointPattern> fpat = new AtomicReference<>(null);
	AtomicReference<Constructor> fcon = new AtomicReference<>(null);
	SleighLanguages.traverseConstructors(lang, new ConstructorEntryVisitor() {
		@Override
		public int visit(SubtableSymbol subtable, DisjointPattern pattern, Constructor cons) {
			if (table.equals(subtable.getName()) &&
				firstPrint.equals(cons.getPrintPieces().get(0))) {
				if (null != fpat.get()) {
					throw new AssertionError("Multiple constructors found. " +
						"Write the test slaspec such that no two constructors in the same " +
						"table share the same first printpiece.");
				}
				fpat.set(pattern);
				fcon.set(cons);
			}
			return CONTINUE;
		}
	});
	if (null == fpat.get()) {
		throw new AssertionError(
			"No such constructor found: " + table + ":" + firstPrint + "...");
	}
	return new ImmutablePair<>(fpat.get(), fcon.get());
}
 
Example #5
Source File: SomaticClusteringModel.java    From gatk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public List<Pair<String, String>> clusteringMetadata() {
    final List<Pair<String, String>> result = new ArrayList<>();
    IntStream.range(-MAX_INDEL_SIZE_IN_PRIOR_MAP, MAX_INDEL_SIZE_IN_PRIOR_MAP + 1).forEach(n -> {
        final double logPrior = logVariantPriors.get(n);
        final String type = n == 0 ? "SNV" :
                (n < 0 ? "deletion" : "insertion") + " of length " + Math.abs(n);
        result.add(ImmutablePair.of("Ln prior of " + type, Double.toString(logPrior)));
    });

    result.add(ImmutablePair.of("Background beta-binomial cluster",
            String.format("weight = %.4f, %s", Math.exp(logClusterWeights[0]), clusters.get(0).toString())));
    result.add(ImmutablePair.of("High-AF beta-binomial cluster",
            String.format("weight = %.4f, %s", Math.exp(logClusterWeights[1]), clusters.get(1).toString())));

    IntStream.range(2, clusters.size()).boxed()
            .sorted(Comparator.comparingDouble(c -> -logClusterWeights[c]))
            .forEach(c -> result.add(ImmutablePair.of("Binomial cluster",
                    String.format("weight = %.4f, %s", Math.exp(logClusterWeights[c]), clusters.get(c).toString()))));
    return result;
}
 
Example #6
Source File: SynchronizedUnivariateSolverUnitTest.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void testManyEquationsInstance(final int numEquations) throws InterruptedException {
    final Function<Map<Integer, Double>, Map<Integer, Double>> func = arg ->
            arg.entrySet().stream()
                    .map(entry -> {
                        final int index = entry.getKey();
                        final double x = entry.getValue();
                        return ImmutablePair.of(index, FastMath.pow(x, index) - index);
                    }).collect(Collectors.toMap(p -> p.left, p -> p.right));
    final SynchronizedUnivariateSolver solver = new SynchronizedUnivariateSolver(func, SOLVER_FACTORY, numEquations);
    for (int n = 1; n <= numEquations; n++) {
        solver.add(n, 0, 2, 0.5, 1e-7, 1e-7, 100);
    }
    final Map<Integer, SynchronizedUnivariateSolver.UnivariateSolverSummary> sol = solver.solve();
    for (int n = 1; n <= numEquations; n++) {
        Assert.assertEquals(sol.get(n).x, FastMath.pow(n, 1.0/n), 1e-6);
    }
}
 
Example #7
Source File: ContentIndexingColumnBasedHandlerTest.java    From datawave with Apache License 2.0 6 votes vote down vote up
public static void SetExpectedMap(String fieldName, String[] expectedResults, String[] expectedReversResults,
                Multimap<String,NormalizedContentInterface> fields, Multimap<String,NormalizedContentInterface> index,
                Multimap<String,NormalizedContentInterface> reverse, Multimap<String,Pair<String,Integer>> tfValues) {
    NormalizedContentInterface template = new NormalizedFieldAndValue();
    template.setFieldName(fieldName);
    
    for (int i = 0; i < expectedResults.length; i++) {
        template.setIndexedFieldValue(expectedResults[i]);
        template.setEventFieldValue(null);
        fields.put(fieldName, new NormalizedFieldAndValue(template));
        index.put(fieldName, new NormalizedFieldAndValue(template));
        
        template.setIndexedFieldValue(expectedReversResults[i]);
        template.setEventFieldValue(expectedReversResults[i]);
        reverse.put(fieldName, new NormalizedFieldAndValue(template));
        
        tfValues.put(fieldName, new ImmutablePair<>(expectedResults[i], i));
    }
}
 
Example #8
Source File: RedeliveryDelayTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Validates message content of redelivered messages against original message. Validate that the redelivery delay
 * has occurred.
 *
 * @param receivedMessages        The received message list.
 * @param originalMessageIndex    The index of the origin message in the received message list.
 * @param redeliveredMessageIndex The index of the redelivered message in the received message list.
 * @param expectedMessageContent  The expected message content.
 */
private void validateMessageContentAndDelay(
        List<ImmutablePair<String, Calendar>> receivedMessages,
        int originalMessageIndex,
        int redeliveredMessageIndex,
        String expectedMessageContent) {
    // Validate message content
    String messageContent = receivedMessages.get(redeliveredMessageIndex).getLeft();
    Assert.assertEquals(messageContent, expectedMessageContent, "Invalid messages received.");

    // Validate delay
    Calendar originalMessageCalendar = receivedMessages.get(originalMessageIndex).getRight();
    log.info("Original message timestamp for " + messageContent + " : " +
             originalMessageCalendar.getTimeInMillis());
    originalMessageCalendar.add(Calendar.SECOND, 10);
    log.info("Minimum redelivered timestamp for " + messageContent + " : " +
             originalMessageCalendar.getTimeInMillis());
    Calendar redeliveredMessageCalendar = receivedMessages.get(redeliveredMessageIndex).getRight();
    log.info("Timestamp of redelivered for " + messageContent + " message : " +
             redeliveredMessageCalendar.getTimeInMillis());
    Assert.assertTrue(originalMessageCalendar.compareTo(redeliveredMessageCalendar) <= 0,
            "Message received before the redelivery delay");
}
 
Example #9
Source File: SlowExample.java    From symbolicautomata with Apache License 2.0 6 votes vote down vote up
/**
 * allCharsExcept() builds a CharPred predicate that accepts any character
 * except for "excluded".  If "excluded" is null, it returns the TRUE
 * predicate.
 *
 * @param excluded the character to exclude
 * @param returnPred whether or not we should generate a return predicate
 * @return the predicate
 */
private static CharPred allCharsExcept(Character excluded,
                                       boolean returnPred){
  if(excluded == null){
    if(returnPred)
      return(SlowExample.TRUE_RET);
    else
      return(StdCharPred.TRUE);
  }

  // weird stuff to avoid Java errors for increment/decrementing chars
  char prev = excluded; prev--;
  char next = excluded; next++;

  return(new CharPred(ImmutableList.of(ImmutablePair.of(CharPred.MIN_CHAR,
                                                        prev),
                                       ImmutablePair.of(next,
                                                        CharPred.MAX_CHAR)),
                                       returnPred));
}
 
Example #10
Source File: AlexaPlatformService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public ListenableFuture<PlatformMessage> request(PlatformMessage msg, Predicate<PlatformMessage> matcher, int timeoutSecs) {
   if(timeoutSecs < 0) {
      timeoutSecs = defaultTimeoutSecs;
   }

   final Address addr = msg.getDestination();
   final SettableFuture<PlatformMessage> future = SettableFuture.create();
   future.addListener(() -> { futures.remove(addr); }, workerPool);

   Predicate<PlatformMessage> pred = (pm) -> { return Objects.equals(msg.getCorrelationId(), pm.getCorrelationId()) && msg.isError(); };
   pred = matcher.or(pred);

   Pair<Predicate<PlatformMessage>, SettableFuture<PlatformMessage>> pair = new ImmutablePair<>(matcher, future);
   futures.put(addr, pair);
   bus.send(msg);
   timeoutPool.newTimeout((timer) -> {
      if(!future.isDone()) {
         future.setException(new TimeoutException("future timed out"));
      }
   }, timeoutSecs, TimeUnit.SECONDS);
   return future;
}
 
Example #11
Source File: Splitter.java    From yauaa with Apache License 2.0 6 votes vote down vote up
public List<Pair<Integer, Integer>> createSplitList(char[] characters){
    List<Pair<Integer, Integer>> result = new ArrayList<>(8);

    int offset = findSplitStart(characters, 1);
    if (offset == -1) {
        return result; // Nothing at all. So we are already done
    }
    while(offset != -1) {

        int start = offset;
        int end= findSplitEnd(characters, start);

        result.add(new ImmutablePair<>(start, end));
        offset = findNextSplitStart(characters, end);
    }
    return result;
}
 
Example #12
Source File: OrderByDocumentQueryExecutionContext.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
private ImmutablePair<Integer, FormattedFilterInfo> GetFiltersForPartitions(
        OrderByContinuationToken orderByContinuationToken,
        List<PartitionKeyRange> partitionKeyRanges,
        List<SortOrder> sortOrders,
        Collection<String> orderByExpressions) throws DocumentClientException {
    // Find the partition key range we left off on
    int startIndex = this.FindTargetRangeAndExtractContinuationTokens(partitionKeyRanges,
            orderByContinuationToken.getCompositeContinuationToken().getRange());

    // Get the filters.
    FormattedFilterInfo formattedFilterInfo = this.GetFormattedFilters(orderByExpressions,
            orderByContinuationToken.getOrderByItems(),
            sortOrders,
            orderByContinuationToken.getInclusive());

    return new ImmutablePair<Integer, FormattedFilterInfo>(startIndex,
            formattedFilterInfo);
}
 
Example #13
Source File: TopicMapView.java    From find with MIT License 6 votes vote down vote up
private List<ImmutablePair<WebElement, Integer>> childConcepts(final int clusterIndex) {
    //((lowestX,highestX),(lowestY,highestY))
    final Double[][] boundariesOfChosenCluster = nthConceptCluster(clusterIndex).getBoundaries();

    final Point mapCoordinates = map().getLocation();
    //L:Concept; Y:Index
    final List<ImmutablePair<WebElement, Integer>> childConceptsOfChosenCluster = new ArrayList<>();

    int entityIndex = 0;
    for(final WebElement concepts : concepts()) {
        final Dimension entitySize = concepts.getSize();
        final Point absolutePosition = concepts.getLocation();

        final int centreX = absolutePosition.x - mapCoordinates.x + entitySize.getWidth() / 2;
        final int centreY = absolutePosition.y - mapCoordinates.y + entitySize.getHeight() / 2;
        final Point centre = new Point(centreX, centreY);

        if(boundariesOfChosenCluster[0][0] <= centre.x && centre.x <= boundariesOfChosenCluster[0][1]
            && boundariesOfChosenCluster[1][0] <= centre.y && centre.y <= boundariesOfChosenCluster[1][1]) {
            childConceptsOfChosenCluster.add(new ImmutablePair<>(concepts, entityIndex));
        }

        entityIndex++;
    }
    return childConceptsOfChosenCluster;
}
 
Example #14
Source File: DeployOvfTemplateService.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
public void deployOvfTemplate(final HttpInputs httpInputs, final VmInputs vmInputs, final String templatePath,
                              final Map<String, String> ovfNetworkMap, final Map<String, String> ovfPropertyMap)
        throws Exception {
    final ConnectionResources connectionResources = new ConnectionResources(httpInputs, vmInputs);
    try {
        final ImmutablePair<ManagedObjectReference, OvfCreateImportSpecResult> pair = createLeaseSetup(connectionResources, vmInputs, templatePath, ovfNetworkMap, ovfPropertyMap);
        final ManagedObjectReference httpNfcLease = pair.getLeft();
        final OvfCreateImportSpecResult importSpecResult = pair.getRight();

        final HttpNfcLeaseInfo httpNfcLeaseInfo = getHttpNfcLeaseInfoWhenReady(connectionResources, httpNfcLease);
        final List<HttpNfcLeaseDeviceUrl> deviceUrls = httpNfcLeaseInfo.getDeviceUrl();
        final ProgressUpdater progressUpdater = executor.isParallel() ?
                new AsyncProgressUpdater(getDisksTotalNoBytes(importSpecResult), httpNfcLease, connectionResources) :
                new SyncProgressUpdater(getDisksTotalNoBytes(importSpecResult), httpNfcLease, connectionResources);

        executor.execute(progressUpdater);
        transferVmdkFiles(templatePath, importSpecResult, deviceUrls, progressUpdater);
        executor.shutdown();
    } finally {
        if (httpInputs.isCloseSession()) {
            connectionResources.getConnection().disconnect();
            clearConnectionFromContext(httpInputs.getGlobalSessionObject());
        }
    }
}
 
Example #15
Source File: QueryManagerTest.java    From bullet-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testCategorizingAll() {
    QueryManager manager = new QueryManager(new BulletConfig());
    Query queryA = getQuery(ImmutablePair.of("A", "foo"));
    Query queryB = getQuery(ImmutablePair.of("A", "foo"), ImmutablePair.of("B", "bar"));
    Querier querierA = getQuerier(queryA);
    Querier querierB = getQuerier(queryB);
    manager.addQuery("idA", querierA);
    manager.addQuery("idB", querierB);

    QueryCategorizer categorizer = manager.categorize();
    Assert.assertEquals(categorizer.getDone().size(), 0);
    Assert.assertEquals(categorizer.getClosed().size(), 0);
    Assert.assertEquals(categorizer.getRateLimited().size(), 0);
    verify(querierA, times(1)).isDone();
    verify(querierA, times(1)).isClosed();
    verify(querierA, times(1)).isExceedingRateLimit();
    verify(querierB, times(1)).isDone();
    verify(querierB, times(1)).isClosed();
    verify(querierB, times(1)).isExceedingRateLimit();
}
 
Example #16
Source File: InFlightConfigReceiverTest.java    From aion with MIT License 6 votes vote down vote up
@Test(expected = RollbackException.class)
public void testApplyNewConfigUnsuccessfulApplierThenRollbackUnsuccessful() throws Exception {
    TestApplier cannotRollbackApplier =
            new TestApplier(TestApplier.Behaviour.THROW_ON_UNDO_ONLY);

    registryMap.put(
            "good.key",
            ImmutablePair.of(cfg -> cfg.getId(), Optional.of(cannotRollbackApplier)));
    registryMap.put(
            "bad.key", ImmutablePair.of(cfg -> cfg.getId(), Optional.of(failingApplier)));
    when(oldCfg.getId()).thenReturn("old");
    when(newCfg.getId()).thenReturn("new");

    InFlightConfigReceiver unit = new InFlightConfigReceiver(oldCfg, registry);
    unit.applyNewConfig(newCfg);
}
 
Example #17
Source File: EvaluateCopyNumberTriStateCalls.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Genotype buildAndAnnotateTruthOverlappingGenotype(final String sample, final VariantContext truth, final List<VariantContext> calls,
                                                          final TargetCollection<Target> targets) {
    final Genotype truthGenotype = truth.getGenotype(sample);
    // if there is no truth genotype for that sample, we output the "empty" genotype.
    if (truthGenotype == null) {
        return GenotypeBuilder.create(sample, Collections.emptyList());
    }
    final int truthCopyNumber = GATKProtectedVariantContextUtils.getAttributeAsInt(truthGenotype,
            GS_COPY_NUMBER_FORMAT_KEY, truthNeutralCopyNumber);
    final CopyNumberTriStateAllele truthAllele = copyNumberToTrueAllele(truthCopyNumber);

    final List<Pair<VariantContext, Genotype>> allCalls = calls.stream()
            .map(vc -> new ImmutablePair<>(vc, vc.getGenotype(sample)))
            .filter(pair -> pair.getRight() != null)
            .filter(pair -> GATKProtectedVariantContextUtils.getAttributeAsString(pair.getRight(), XHMMSegmentGenotyper.DISCOVERY_KEY,
                    XHMMSegmentGenotyper.DISCOVERY_FALSE).equals(XHMMSegmentGenotyper.DISCOVERY_TRUE))
            .collect(Collectors.toList());

    final List<Pair<VariantContext, Genotype>> qualifiedCalls = composeQualifyingCallsList(targets, allCalls);

    return buildAndAnnotateTruthOverlappingGenotype(sample, targets, truthGenotype, truthCopyNumber,
                truthAllele, qualifiedCalls);
}
 
Example #18
Source File: ClientSideMetrics.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
/**
 * Constructor
 *
 * @param retries             The number of retries required to execute the query.
 * @param requestCharge       The request charge incurred from executing the query.
 * @param executionRanges     The fetch execution ranges from executing the query.
 * @param schedulingTimeSpans The partition scheduling timespans from the query.
 */
public ClientSideMetrics(int retries, double requestCharge, List<FetchExecutionRange> executionRanges,
                         List<ImmutablePair<String, SchedulingTimeSpan>> schedulingTimeSpans) {
    if (executionRanges == null || executionRanges.contains(null)) {
        throw new NullPointerException("executionRanges");
    }
    if (schedulingTimeSpans == null || schedulingTimeSpans.contains(null)) {
        throw new NullPointerException("schedulingTimeSpans");
    }
    if (retries < 0) {
        throw new IllegalArgumentException("retries must not be negative");
    }
    if (requestCharge < 0) {
        throw new IllegalArgumentException("requestCharge must not be negative");
    }

    this.retries = retries;
    this.requestCharge = requestCharge;
    this.fetchExecutionRanges = executionRanges;
    this.partitionSchedulingTimeSpans = schedulingTimeSpans;
}
 
Example #19
Source File: NetworkV1ToNetworkV4ConverterTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertToStackRequestWhenAzurePresentedWithSubnet() {
    NetworkV1Request networkV1Request = azureNetworkV1Request();
    DetailedEnvironmentResponse environmentNetworkResponse = azureEnvironmentNetwork();


    NetworkV4Request networkV4Request = underTest
            .convertToNetworkV4Request(new ImmutablePair<>(networkV1Request, environmentNetworkResponse));

    Assert.assertEquals(networkV4Request.createAzure().getNetworkId(), VPC_ID);
    Assert.assertEquals(networkV4Request.createAzure().getResourceGroupName(), GROUP_NAME);
    Assert.assertEquals(networkV4Request.createAzure().getSubnetId(), SUBNET_ID);
}
 
Example #20
Source File: Rgaa30Rule050703.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Default constructor
 */
public Rgaa30Rule050703() {
    super(
            new SimpleElementSelector(TABLE_WITH_TH_CSS_LIKE_QUERY),

            // the data and complex tables are part of the scope
            new String[]{DATA_TABLE_MARKER, COMPLEX_TABLE_MARKER},

            // the presentation tables are not part of the scope
            new String[]{PRESENTATION_TABLE_MARKER},

            // checker for elements identified by marker
            new ElementPresenceChecker(
                // nmi when element is found
                new ImmutablePair(TestSolution.NEED_MORE_INFO, CHECK_DEFINITION_OF_HEADERS_FOR_DATA_TABLE_MSG),
                // na when element is not found
                new ImmutablePair(TestSolution.NOT_APPLICABLE, "")
            ), 
            
            // checker for elements not identified by marker
            new ElementPresenceChecker(
                // nmi when element is found
                new ImmutablePair(TestSolution.NEED_MORE_INFO, CHECK_NATURE_OF_TABLE_AND_HEADERS_DEFINITION_MSG),
                // na when element is not found
                new ImmutablePair(TestSolution.NOT_APPLICABLE, "")
            )
        );
}
 
Example #21
Source File: HdfsUploader.java    From terrapin with Apache License 2.0 5 votes vote down vote up
@Override
List<Pair<Path, Long>> getFileList() {
  List<Pair<Path, Long>> fileSizePairList = Lists.newArrayList();
  try {
    List<HdfsFileStatus> fileStatusList = TerrapinUtil.getHdfsFileList(dfsClient, hdfsDir.toString());
    for (HdfsFileStatus fileStatus : fileStatusList) {
      fileSizePairList.add(new ImmutablePair(fileStatus.getFullPath(hdfsDir), fileStatus.getLen()));
    }
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  return fileSizePairList;
}
 
Example #22
Source File: OrderController.java    From tcc-transaction with Apache License 2.0 5 votes vote down vote up
private PlaceOrderRequest buildRequest(String redPacketPayAmount, long shopId, long payerUserId, long productId) {
    BigDecimal redPacketPayAmountInBigDecimal = new BigDecimal(redPacketPayAmount);
    if (redPacketPayAmountInBigDecimal.compareTo(BigDecimal.ZERO) < 0)
        throw new InvalidParameterException("invalid red packet amount :" + redPacketPayAmount);

    PlaceOrderRequest request = new PlaceOrderRequest();
    request.setPayerUserId(payerUserId);
    request.setShopId(shopId);
    request.setRedPacketPayAmount(new BigDecimal(redPacketPayAmount));
    request.getProductQuantities().add(new ImmutablePair<Long, Integer>(productId, 1));
    return request;
}
 
Example #23
Source File: HttpContentSizeValidatorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testUrlFailsWithMoreThanMax() {
    when(httpHelper.getContentLength(anyString())).thenReturn(new ImmutablePair<>(statusType, MAX_IN_BYTES + 1));

    assertFalse(underTest.isValid("http://big.content.com", constraintValidatorContext));

    verify(constraintValidatorContext, times(0)).buildConstraintViolationWithTemplate(anyString());
}
 
Example #24
Source File: Rgaa30Rule010701.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Default constructor
 */
public Rgaa30Rule010701() {
    super(
            new ImageElementSelector(
                    new MultipleElementSelector(
                            FORM_BUTTON_CSS_LIKE_QUERY,
                            IMG_NOT_IN_LINK_CSS_LIKE_QUERY    
                    )
            ),

            // the informative images are part of the scope
            INFORMATIVE_IMAGE_MARKER, 

            // the decorative images are not part of the scope
            DECORATIVE_IMAGE_MARKER, 
            
            // checker for elements identified by marker
            new ElementPresenceChecker(
                // solution when at least one element is found
                new ImmutablePair(TestSolution.NEED_MORE_INFO,CHECK_DESC_PERTINENCE_OF_INFORMATIVE_IMG_MSG),
                // solution when no element is found
                new ImmutablePair(TestSolution.NOT_APPLICABLE,""), 
                // evidence elements
                ALT_ATTR, 
                SRC_ATTR), 
            
            // checker for elements not identified by marker
            new ElementPresenceChecker(
                // solution when at least one element is found
                new ImmutablePair(TestSolution.NEED_MORE_INFO,CHECK_NATURE_OF_IMAGE_AND_DESC_PERTINENCE_MSG),
                // solution when no element is found
                new ImmutablePair(TestSolution.NOT_APPLICABLE,""), 
                // evidence elements
                ALT_ATTR, 
                SRC_ATTR)
        );
}
 
Example #25
Source File: DownloadServiceImpl.java    From genie with Apache License 2.0 5 votes vote down vote up
private ManifestImpl(final Map<URI, File> uriFileMap) {

            this.uriFileMap = Collections.unmodifiableMap(uriFileMap);

            this.targetDirectories = Collections.unmodifiableSet(
                uriFileMap
                    .values()
                    .stream()
                    .map(File::getParentFile)
                    .collect(Collectors.toSet())
            );

            this.targetFiles = Collections.unmodifiableSet(
                Sets.newHashSet(uriFileMap.values())
            );

            if (targetFiles.size() < uriFileMap.values().size()) {
                throw new IllegalArgumentException("Two or more files are targeting the same destination location");
            }

            this.sourceFileUris = Collections.unmodifiableSet(uriFileMap.keySet());

            this.entries = Collections.unmodifiableSet(
                uriFileMap.entrySet()
                    .stream()
                    .map(entry -> new ImmutablePair<>(entry.getKey(), entry.getValue()))
                    .collect(Collectors.toSet())
            );
        }
 
Example #26
Source File: Rgaa30Rule010404.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Default constructor
 */
public Rgaa30Rule010404 () {
    super(
            new CaptchaElementSelector(
                new SimpleElementSelector(OBJECT_TYPE_IMG_NOT_IN_LINK_CSS_LIKE_QUERY)),
            // solution when at least one element is found
            new ImmutablePair(TestSolution.NEED_MORE_INFO,CHECK_CAPTCHA_ALTERNATIVE_MSG),
            // solution when no element is found
            new ImmutablePair(TestSolution.NOT_APPLICABLE,""),
            // evidence elements
            TEXT_ELEMENT2, 
            DATA_ATTR
        );
}
 
Example #27
Source File: Rgaa32016Rule010607.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Default constructor
 */
public Rgaa32016Rule010607 () {
    super(
            new ImageElementSelector(
                    new MultipleElementSelector(
                            SVG_NOT_IN_LINK_WITH_DESC_CHILD_CSS_LIKE_QUERY,
                            SVG_NOT_IN_LINK_WITH_ARIA_LABEL_CSS_LIKE_QUERY)),

            // the informative images are part of the scope
            INFORMATIVE_IMAGE_MARKER, 

            // the decorative images are not part of the scope
            DECORATIVE_IMAGE_MARKER, 

            // checker for elements identified by marker
            new ElementPresenceChecker(
                // solution when at least one element is found
                new ImmutablePair(TestSolution.NEED_MORE_INFO,CHECK_AT_RESTITUTION_OF_DESC_OF_INFORMATIVE_IMG_MSG),
                // solution when no element is found
                new ImmutablePair(TestSolution.NOT_APPLICABLE,""), 
                // evidence elements
                TEXT_ELEMENT2,
                ARIA_LABEL_ATTR),
            
            // checker for elements not identified by marker
            new ElementPresenceChecker(
                // solution when at least one element is found
                new ImmutablePair(TestSolution.NEED_MORE_INFO,CHECK_NATURE_OF_IMAGE_AND_AT_RESTITUTION_OF_PERTINENCE_MSG),
                // solution when no element is found
                new ImmutablePair(TestSolution.NOT_APPLICABLE,""), 
                // evidence elements
                TEXT_ELEMENT2,
                ARIA_LABEL_ATTR)
        );
}
 
Example #28
Source File: ScoringMNVTest.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void correctlyComputes50PercentFrequency() {
    final List<Pair<VariantScore, VariantScore>> mnvScores = Lists.newArrayList();
    mnvScores.add(ImmutablePair.of(ImmutableVariantScore.of(ReadType.ALT, 10), ImmutableVariantScore.of(ReadType.REF, 20)));
    mnvScores.add(ImmutablePair.of(ImmutableVariantScore.of(ReadType.ALT, 15), ImmutableVariantScore.of(ReadType.ALT, 15)));
    final MNVScore scores = build2VariantScores(Lists.newArrayList(VARIANTS.get(0), VARIANTS.get(1)), mnvScores);
    assertEquals(0.5, scores.frequency(), 0.000001);
}
 
Example #29
Source File: Rgaa30Rule010309.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 *
 * @return the checker user for marked elements
 */
private ElementChecker getLocalRegularElementChecker() {
    ElementChecker ec = new ElementPresenceChecker(
            new ImmutablePair(TestSolution.NEED_MORE_INFO, CHECK_NATURE_OF_IMAGE_AND_ALT_PERTINENCE_MSG),
            new ImmutablePair(TestSolution.NOT_APPLICABLE, ""),
            // evidence element
            TEXT_ELEMENT2
    );
    return ec;
}
 
Example #30
Source File: SetCoverageTest.java    From jMetal with MIT License 5 votes vote down vote up
@Test
public void shouldExecuteRaiseAnExceptionIfTheFirstFrontIsNull() {
  exception.expect(JMetalException.class);
  exception.expectMessage(containsString("The first front is null"));

  List<Solution<DoubleSolution>> frontA = null ;
  List<Solution<DoubleSolution>> frontB = new ArrayList<>() ;

  setCoverage.evaluate(new ImmutablePair<List<? extends Solution<?>>, List<? extends Solution<?>>>(frontA, frontB));
}