Java Code Examples for java.util.SortedMap#isEmpty()

The following examples show how to use java.util.SortedMap#isEmpty() . 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: HFilePrettyPrinter.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Override
public void report(SortedMap<String, Gauge> gauges,
                   SortedMap<String, Counter> counters,
                   SortedMap<String, Histogram> histograms,
                   SortedMap<String, Meter> meters,
                   SortedMap<String, Timer> timers) {
  // we know we only have histograms
  if (!histograms.isEmpty()) {
    for (Map.Entry<String, Histogram> entry : histograms.entrySet()) {
      output.print("   " + StringUtils.substringAfterLast(entry.getKey(), "."));
      output.println(':');
      printHistogram(entry.getValue());
    }
    output.println();
  }

  output.println();
  output.flush();
}
 
Example 2
Source File: UsageStatisticsCollectorImpl.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
private @Nullable <T> T getGaugeValue(final String metricName) {
    try {
        final SortedMap<String, Gauge> gauges = metricsHolder.getMetricRegistry().getGauges((name, metric) -> metricName.equals(name));
        if (gauges.isEmpty()) {
            return null;
        }

        //we expect a single result here
        final Gauge gauge = gauges.values().iterator().next();

        final T value = (T) gauge.getValue();
        return value;
    } catch (final Exception e) {
        return null;
    }
}
 
Example 3
Source File: ConsistentHash.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
/**
 * This returns the closest node for the object. If the object is the node it
 * should be an exact hit, but if it is a value traverse to find closest
 * subsequent node.
 * @param key the key 
 * @return node for
 */
public T getNodeFor(Object key) {
    if (circle.isEmpty()) {
        return null;
    }
    int hash = hashFunction.hash(key);
    T node = circle.get(hash);

    if (node == null) {
        // inexact match -- find the next value in the circle
        SortedMap<Integer, T> tailMap = circle.tailMap(hash);
        hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
        node = circle.get(hash);
    }
    return node;
}
 
Example 4
Source File: HealthCheckHandler.java    From pippo with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RouteContext routeContext) {
    Response response = routeContext.getResponse().noCache().text();

    SortedMap<String, HealthCheck.Result> healthChecks = healthCheckRegistry.runHealthChecks();
    if (healthChecks.isEmpty()) {
        response.notImplemented().send("The health checks are empty");
    } else {
        boolean notHealthy = healthChecks.values().stream().anyMatch(hc -> !hc.isHealthy());
        if (notHealthy) {
            response.internalError().send("The health is bad");
        } else {
            response.ok().send("The health is good");
        }
    }
}
 
Example 5
Source File: PartitionByMurmurHash.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Integer calculate(String columnValue) {
	SortedMap<Integer, Integer> tail = bucketMap.tailMap(hash.hashUnencodedChars(columnValue).asInt());
	if (tail.isEmpty()) {
	    return bucketMap.get(bucketMap.firstKey());
	}
	return tail.get(tail.firstKey());
}
 
Example 6
Source File: ConsistentHashRouter.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
/**
 * with a specified key, route the nearest Node instance in the current hash ring
 *
 * @param objectKey the object key to find a nearest Node
 */
public T routeNode(String objectKey) {
    if (ring.isEmpty()) {
        return null;
    }
    Long hashVal = hashFunction.hash(objectKey);
    SortedMap<Long, VirtualNode<T>> tailMap = ring.tailMap(hashVal);
    Long nodeHashVal = !tailMap.isEmpty() ? tailMap.firstKey() : ring.firstKey();
    return ring.get(nodeHashVal).getPhysicalNode();
}
 
Example 7
Source File: AggregatingSelectScope.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Resolved resolve() {
  final ImmutableList.Builder<ImmutableList<ImmutableBitSet>> builder =
      ImmutableList.builder();
  List<SqlNode> extraExprs = ImmutableList.of();
  Map<Integer, Integer> groupExprProjection = ImmutableMap.of();
  if (select.getGroup() != null) {
    final SqlNodeList groupList = select.getGroup();
    final SqlValidatorUtil.GroupAnalyzer groupAnalyzer =
        new SqlValidatorUtil.GroupAnalyzer(temporaryGroupExprList);
    for (SqlNode groupExpr : groupList) {
      SqlValidatorUtil.analyzeGroupItem(this, groupAnalyzer, builder,
          groupExpr);
    }
    extraExprs = groupAnalyzer.extraExprs;
    groupExprProjection = groupAnalyzer.groupExprProjection;
  }

  final SortedMap<ImmutableBitSet, Integer> flatGroupSetCount =
      Maps.newTreeMap(ImmutableBitSet.COMPARATOR);
  for (List<ImmutableBitSet> groupSet : Linq4j.product(builder.build())) {
    final ImmutableBitSet set = ImmutableBitSet.union(groupSet);
    flatGroupSetCount.put(set, flatGroupSetCount.getOrDefault(set, 0) + 1);
  }

  // For GROUP BY (), we need a singleton grouping set.
  if (flatGroupSetCount.isEmpty()) {
    flatGroupSetCount.put(ImmutableBitSet.of(), 1);
  }

  return new Resolved(extraExprs, temporaryGroupExprList, flatGroupSetCount.keySet(),
      flatGroupSetCount, groupExprProjection);
}
 
Example 8
Source File: AnnotationViewDataImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static int findNextUsedLine(int from, SortedMap<Integer, List<Mark>> marks) {
    SortedMap<Integer, List<Mark>> next = marks.tailMap(from + 1);
    
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("AnnotationView.findNextUsedLine from: " + from + "; marks: " + marks + "; next: " + next); //NOI18N
    }
    
    if (next.isEmpty()) {
        return Integer.MAX_VALUE;
    }
    
    return next.firstKey().intValue();
}
 
Example 9
Source File: ST.java    From java_jail with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns the largest key in the symbol table less than or equal to <tt>key</tt>.
 * @return the largest key in the symbol table less than or equal to <tt>key</tt>
 * @param key the key
 * @throws NoSuchElementException if the symbol table is empty
 * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>
 */
public Key floor(Key key) {
    if (key == null) throw new NullPointerException("called floor() with null key");
    // headMap does not include key if present (!)
    if (st.containsKey(key)) return key;
    SortedMap<Key, Value> head = st.headMap(key);
    if (head.isEmpty()) throw new NoSuchElementException();
    return head.lastKey();
}
 
Example 10
Source File: InMemoryPlan.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public Set<ReservationAllocation> getReservationsAtTime(long tick) {
  ReservationInterval searchInterval =
      new ReservationInterval(tick, Long.MAX_VALUE);
  readLock.lock();
  try {
    SortedMap<ReservationInterval, Set<InMemoryReservationAllocation>> reservations =
        currentReservations.headMap(searchInterval, true);
    if (!reservations.isEmpty()) {
      Set<ReservationAllocation> flattenedReservations =
          new HashSet<ReservationAllocation>();
      for (Set<InMemoryReservationAllocation> reservationEntries : reservations
          .values()) {
        for (InMemoryReservationAllocation reservation : reservationEntries) {
          if (reservation.getEndTime() > tick) {
            flattenedReservations.add(reservation);
          }
        }
      }
      return Collections.unmodifiableSet(flattenedReservations);
    } else {
      return Collections.emptySet();
    }
  } finally {
    readLock.unlock();
  }
}
 
Example 11
Source File: Filter.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
static private long getAppropriateSeq(SortedMap<Long, AppVersion> timeStamps, long when, boolean roundToLaterVersion) {
    if (roundToLaterVersion) {
        SortedMap<Long, AppVersion> geq = timeStamps.tailMap(when);
        if (geq.isEmpty()) {
            return Long.MAX_VALUE;
        }
        return geq.get(geq.firstKey()).getSequenceNumber();
    } else {
        SortedMap<Long, AppVersion> leq = timeStamps.headMap(when);
        if (leq.isEmpty()) {
            return Long.MIN_VALUE;
        }
        return leq.get(leq.lastKey()).getSequenceNumber();
    }
}
 
Example 12
Source File: ConsistentHashRouter.java    From rocketmq-read with Apache License 2.0 5 votes vote down vote up
/**
 * with a specified key, route the nearest Node instance in the current hash ring
 * 路由到一个物理节点
 * @param objectKey the object key to find a nearest Node
 */
public T routeNode(String objectKey) {
    if (ring.isEmpty()) {
        return null;
    }
    Long hashVal = hashFunction.hash(objectKey);
    SortedMap<Long, VirtualNode<T>> tailMap = ring.tailMap(hashVal);
    Long nodeHashVal = !tailMap.isEmpty() ? tailMap.firstKey() : ring.firstKey();
    return ring.get(nodeHashVal).getPhysicalNode();
}
 
Example 13
Source File: ConsistentHashRoutingService.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
private synchronized Pair<Long, SocketAddress> get(long hash) {
    if (circle.isEmpty()) {
        return null;
    }

    if (!circle.containsKey(hash)) {
        SortedMap<Long, SocketAddress> tailMap = circle.tailMap(hash);
        hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
    }
    return Pair.of(hash, circle.get(hash));
}
 
Example 14
Source File: Vertex.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public Vertex getNextVertexOnDest() {
  SortedMap<Long, Vertex> map = graph.getIndexedVertices().get(name);
  SortedMap<Long, Vertex> tailMap = map.tailMap(timestamp + 1);
  if(tailMap.isEmpty()) {
    return null;
  } else {
    return tailMap.get(tailMap.firstKey());
  }
}
 
Example 15
Source File: EnvHelp.java    From JDKSourceCode1.8 with MIT License 4 votes vote down vote up
private static void hideAttributes(SortedMap<String, ?> map) {
    if (map.isEmpty())
        return;

    final SortedSet<String> hiddenStrings;
    final SortedSet<String> hiddenPrefixes;

    String hide = (String) map.get(HIDDEN_ATTRIBUTES);
    if (hide != null) {
        if (hide.startsWith("="))
            hide = hide.substring(1);
        else
            hide += " " + DEFAULT_HIDDEN_ATTRIBUTES;
        hiddenStrings = new TreeSet<String>();
        hiddenPrefixes = new TreeSet<String>();
        parseHiddenAttributes(hide, hiddenStrings, hiddenPrefixes);
    } else {
        hide = DEFAULT_HIDDEN_ATTRIBUTES;
        synchronized (defaultHiddenStrings) {
            if (defaultHiddenStrings.isEmpty()) {
                parseHiddenAttributes(hide,
                                      defaultHiddenStrings,
                                      defaultHiddenPrefixes);
            }
            hiddenStrings = defaultHiddenStrings;
            hiddenPrefixes = defaultHiddenPrefixes;
        }
    }

    /* Construct a string that is greater than any key in the map.
       Setting a string-to-match or a prefix-to-match to this string
       guarantees that we will never call next() on the corresponding
       iterator.  */
    String sentinelKey = map.lastKey() + "X";
    Iterator<String> keyIterator = map.keySet().iterator();
    Iterator<String> stringIterator = hiddenStrings.iterator();
    Iterator<String> prefixIterator = hiddenPrefixes.iterator();

    String nextString;
    if (stringIterator.hasNext())
        nextString = stringIterator.next();
    else
        nextString = sentinelKey;
    String nextPrefix;
    if (prefixIterator.hasNext())
        nextPrefix = prefixIterator.next();
    else
        nextPrefix = sentinelKey;

    /* Read each key in sorted order and, if it matches a string
       or prefix, remove it. */
keys:
    while (keyIterator.hasNext()) {
        String key = keyIterator.next();

        /* Continue through string-match values until we find one
           that is either greater than the current key, or equal
           to it.  In the latter case, remove the key.  */
        int cmp = +1;
        while ((cmp = nextString.compareTo(key)) < 0) {
            if (stringIterator.hasNext())
                nextString = stringIterator.next();
            else
                nextString = sentinelKey;
        }
        if (cmp == 0) {
            keyIterator.remove();
            continue keys;
        }

        /* Continue through the prefix values until we find one
           that is either greater than the current key, or a
           prefix of it.  In the latter case, remove the key.  */
        while (nextPrefix.compareTo(key) <= 0) {
            if (key.startsWith(nextPrefix)) {
                keyIterator.remove();
                continue keys;
            }
            if (prefixIterator.hasNext())
                nextPrefix = prefixIterator.next();
            else
                nextPrefix = sentinelKey;
        }
    }
}
 
Example 16
Source File: EnvHelp.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static void hideAttributes(SortedMap<String, ?> map) {
    if (map.isEmpty())
        return;

    final SortedSet<String> hiddenStrings;
    final SortedSet<String> hiddenPrefixes;

    String hide = (String) map.get(HIDDEN_ATTRIBUTES);
    if (hide != null) {
        if (hide.startsWith("="))
            hide = hide.substring(1);
        else
            hide += " " + DEFAULT_HIDDEN_ATTRIBUTES;
        hiddenStrings = new TreeSet<String>();
        hiddenPrefixes = new TreeSet<String>();
        parseHiddenAttributes(hide, hiddenStrings, hiddenPrefixes);
    } else {
        hide = DEFAULT_HIDDEN_ATTRIBUTES;
        synchronized (defaultHiddenStrings) {
            if (defaultHiddenStrings.isEmpty()) {
                parseHiddenAttributes(hide,
                                      defaultHiddenStrings,
                                      defaultHiddenPrefixes);
            }
            hiddenStrings = defaultHiddenStrings;
            hiddenPrefixes = defaultHiddenPrefixes;
        }
    }

    /* Construct a string that is greater than any key in the map.
       Setting a string-to-match or a prefix-to-match to this string
       guarantees that we will never call next() on the corresponding
       iterator.  */
    String sentinelKey = map.lastKey() + "X";
    Iterator<String> keyIterator = map.keySet().iterator();
    Iterator<String> stringIterator = hiddenStrings.iterator();
    Iterator<String> prefixIterator = hiddenPrefixes.iterator();

    String nextString;
    if (stringIterator.hasNext())
        nextString = stringIterator.next();
    else
        nextString = sentinelKey;
    String nextPrefix;
    if (prefixIterator.hasNext())
        nextPrefix = prefixIterator.next();
    else
        nextPrefix = sentinelKey;

    /* Read each key in sorted order and, if it matches a string
       or prefix, remove it. */
keys:
    while (keyIterator.hasNext()) {
        String key = keyIterator.next();

        /* Continue through string-match values until we find one
           that is either greater than the current key, or equal
           to it.  In the latter case, remove the key.  */
        int cmp = +1;
        while ((cmp = nextString.compareTo(key)) < 0) {
            if (stringIterator.hasNext())
                nextString = stringIterator.next();
            else
                nextString = sentinelKey;
        }
        if (cmp == 0) {
            keyIterator.remove();
            continue keys;
        }

        /* Continue through the prefix values until we find one
           that is either greater than the current key, or a
           prefix of it.  In the latter case, remove the key.  */
        while (nextPrefix.compareTo(key) <= 0) {
            if (key.startsWith(nextPrefix)) {
                keyIterator.remove();
                continue keys;
            }
            if (prefixIterator.hasNext())
                nextPrefix = prefixIterator.next();
            else
                nextPrefix = sentinelKey;
        }
    }
}
 
Example 17
Source File: CryptographicHashAttribute.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }
    final Charset charset = Charset.forName(context.getProperty(CHARACTER_SET).getValue());
    final Map<String, String> attributeToGeneratedNameMap = attributeToGenerateNameMapRef.get();
    final ComponentLog logger = getLogger();

    final SortedMap<String, String> relevantAttributes = getRelevantAttributes(flowFile, attributeToGeneratedNameMap);
    if (relevantAttributes.isEmpty()) {
        if (context.getProperty(FAIL_WHEN_EMPTY).asBoolean()) {
            logger.info("Routing {} to 'failure' because of missing all attributes: {}", new Object[]{flowFile, getMissingKeysString(null, attributeToGeneratedNameMap.keySet())});
            session.transfer(flowFile, REL_FAILURE);
            return;
        }
    }
    if (relevantAttributes.size() != attributeToGeneratedNameMap.size()) {
        if (PartialAttributePolicy.valueOf(context.getProperty(PARTIAL_ATTR_ROUTE_POLICY).getValue()) == PartialAttributePolicy.PROHIBIT) {
            logger.info("Routing {} to 'failure' because of missing attributes: {}", new Object[]{flowFile,
                    getMissingKeysString(relevantAttributes.keySet(), attributeToGeneratedNameMap.keySet())});
            session.transfer(flowFile, REL_FAILURE);
            return;
        }
    }

    // Determine the algorithm to use
    final String algorithmName = context.getProperty(HASH_ALGORITHM).getValue();
    logger.debug("Using algorithm {}", new Object[]{algorithmName});
    HashAlgorithm algorithm = HashAlgorithm.fromName(algorithmName);

    // Generate a hash with the configured algorithm for each attribute value
    // and create a new attribute with the configured name
    for (final Map.Entry<String, String> entry : relevantAttributes.entrySet()) {
        logger.debug("Generating {} hash of attribute '{}'", new Object[]{algorithmName, entry.getKey()});
        String value = hashValue(algorithm, entry.getValue(), charset);
        session.putAttribute(flowFile, attributeToGeneratedNameMap.get(entry.getKey()), value);
    }
    session.getProvenanceReporter().modifyAttributes(flowFile);
    session.transfer(flowFile, REL_SUCCESS);
}
 
Example 18
Source File: Actions.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * Finds Artifact prefix conflicts between generated artifacts. An artifact prefix conflict
 * happens if one action generates an artifact whose path is a prefix of another artifact's path.
 * Those two artifacts cannot exist simultaneously in the output tree.
 *
 * @param actionGraph the {@link ActionGraph} to query for artifact conflicts
 * @param artifactPathMap a map mapping generated artifacts to their exec paths. The map must be
 *     sorted using the comparator from {@link #comparatorForPrefixConflicts()}.
 * @param strictConflictChecks report path prefix conflicts, regardless of
 *     shouldReportPathPrefixConflict().
 * @return A map between actions that generated the conflicting artifacts and their associated
 *     {@link ArtifactPrefixConflictException}.
 */
public static Map<ActionAnalysisMetadata, ArtifactPrefixConflictException>
    findArtifactPrefixConflicts(
        ActionGraph actionGraph,
        SortedMap<PathFragment, Artifact> artifactPathMap,
        boolean strictConflictChecks) {
  // You must construct the sorted map using this comparator for the algorithm to work.
  // The algorithm requires subdirectories to immediately follow parent directories,
  // before any files in that directory.
  // Example: "foo", "foo.obj", foo/bar" must be sorted
  // "foo", "foo/bar", foo.obj"
  Preconditions.checkArgument(
      artifactPathMap.comparator() instanceof PathFragmentPrefixComparator,
      "artifactPathMap must be sorted with PathFragmentPrefixComparator");
  // No actions in graph -- currently happens only in tests. Special-cased because .next() call
  // below is unconditional.
  if (artifactPathMap.isEmpty()) {
    return ImmutableMap.<ActionAnalysisMetadata, ArtifactPrefixConflictException>of();
  }

  // Keep deterministic ordering of bad actions.
  Map<ActionAnalysisMetadata, ArtifactPrefixConflictException> badActions = new LinkedHashMap<>();
  Iterator<PathFragment> iter = artifactPathMap.keySet().iterator();

  // Report an error for every derived artifact which is a prefix of another.
  // If x << y << z (where x << y means "y starts with x"), then we only report (x,y), (x,z), but
  // not (y,z).
  for (PathFragment pathJ = iter.next(); iter.hasNext(); ) {
    // For each comparison, we have a prefix candidate (pathI) and a suffix candidate (pathJ).
    // At the beginning of the loop, we set pathI to the last suffix candidate, since it has not
    // yet been tested as a prefix candidate, and then set pathJ to the paths coming after pathI,
    // until we come to one that does not contain pathI as a prefix. pathI is then verified not to
    // be the prefix of any path, so we start the next run of the loop.
    PathFragment pathI = pathJ;
    // Compare pathI to the paths coming after it.
    while (iter.hasNext()) {
      pathJ = iter.next();
      if (pathJ.startsWith(pathI)) { // prefix conflict.
        Artifact artifactI = Preconditions.checkNotNull(artifactPathMap.get(pathI), pathI);
        Artifact artifactJ = Preconditions.checkNotNull(artifactPathMap.get(pathJ), pathJ);

        // We ignore the artifact prefix conflict between a TreeFileArtifact and its parent
        // TreeArtifact.
        // We can only have such a conflict here if:
        // 1. The TreeArtifact is generated by an ActionTemplate. And the TreeFileArtifact is
        //    generated by an expanded action created at execution time from the ActionTemplate.
        // 2. This is an incremental build with invalidated configured targets. In this case,
        //    the action graph contains expanded actions from previous builds and they will be
        //    checked for artifact conflicts.
        if (artifactJ.hasParent() && artifactJ.getParent().equals(artifactI)) {
          continue;
        }

        ActionAnalysisMetadata actionI =
            Preconditions.checkNotNull(actionGraph.getGeneratingAction(artifactI), artifactI);
        ActionAnalysisMetadata actionJ =
            Preconditions.checkNotNull(actionGraph.getGeneratingAction(artifactJ), artifactJ);
        if (strictConflictChecks || actionI.shouldReportPathPrefixConflict(actionJ)) {
          ArtifactPrefixConflictException exception = new ArtifactPrefixConflictException(pathI,
              pathJ, actionI.getOwner().getLabel(), actionJ.getOwner().getLabel());
          badActions.put(actionI, exception);
          badActions.put(actionJ, exception);
        }
      } else { // pathJ didn't have prefix pathI, so no conflict possible for pathI.
        break;
      }
    }
  }
  return ImmutableMap.copyOf(badActions);
}
 
Example 19
Source File: ProductQuantityStrategyDefaultImpl.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public QuantityModel getQuantityModel(final long shopId,
                                      final BigDecimal cartQty,
                                      final Product product,
                                      final String supplier) {

    final Map<String, Warehouse> warehouses = warehouseService.getByShopIdMapped(shopId, false);
    final Warehouse warehouse = warehouses.get(supplier);
    final Map<String, BigDecimal> qty = new HashMap<>();

    final SortedMap<Integer, SkuWarehouse> rankedInventory = new TreeMap<>();
    for (final ProductSku sku : product.getSku()) {

        final SkuWarehouse inventory = inventoryResolver.findByWarehouseSku(warehouse, sku.getCode());
        if (inventory != null) {
            rankedInventory.put(sku.getRank(), inventory);
            qty.put(inventory.getSkuCode(), inventory.getAvailableToSell());
        }

    }

    if (!rankedInventory.isEmpty()) {
        final LocalDateTime now = now();
        for (final SkuWarehouse first : rankedInventory.values()) {

            final boolean availableNow = first.isAvailable(now);
            if (availableNow) {
                return new QuantityModelImpl(
                        supplier,
                        first.getSkuCode(),
                        first.getMinOrderQuantity(),
                        first.getMaxOrderQuantity(),
                        first.getStepOrderQuantity(),
                        cartQty
                );
            }
        }
    }

    return new QuantityModelImpl(
            supplier,
            product.getCode(),
            null,
            null,
            null,
            cartQty
    );
}
 
Example 20
Source File: MzTabImportTask.java    From mzmine3 with GNU General Public License v2.0 3 votes vote down vote up
private void importVariables(MZTabFile mzTabFile, Map<Integer, RawDataFile> rawDataFiles) {

    // Add sample parameters if available in mzTab file
    SortedMap<Integer, StudyVariable> variableMap = mzTabFile.getMetadata().getStudyVariableMap();

    if (variableMap.isEmpty())
      return;

    UserParameter<?, ?> newParameter =
        new StringParameter(inputFile.getName() + " study variable", "");
    project.addParameter(newParameter);

    for (Entry<Integer, StudyVariable> entry : variableMap.entrySet()) {

      // Stop the process if cancel() was called
      if (isCanceled())
        return;

      String variableValue = entry.getValue().getDescription();

      SortedMap<Integer, Assay> assayMap = entry.getValue().getAssayMap();

      for (Entry<Integer, RawDataFile> rawDataEntry : rawDataFiles.entrySet()) {

        RawDataFile rawData = rawDataEntry.getValue();
        Assay dataFileAssay = assayMap.get(rawDataEntry.getKey());
        if (dataFileAssay != null)
          project.setParameterValue(newParameter, rawData, variableValue);
      }

    }

  }