Example usage for com.google.common.collect Range singleton

List of usage examples for com.google.common.collect Range singleton

Introduction

In this page you can find the example usage for com.google.common.collect Range singleton.

Prototype

public static <C extends Comparable<?>> Range<C> singleton(C value) 

Source Link

Document

Returns a range that Range#contains(Comparable) contains only the given value.

Usage

From source file:com.comphenix.protocol.RangeParser.java

/**
 * Parse ranges from an array of elements.
 * @param args - array of elements.//from   w w  w .  jav a 2s. c o m
 * @param offset - beginning offset.
 * @param lastIndex - the last index of the array to read.
 * @param legalRange - range of legal values.
 * @return The parsed ranges.
 */
public static List<Range<Integer>> getRanges(Deque<String> input, Range<Integer> legalRange) {
    List<String> tokens = tokenizeInput(input);
    List<Range<Integer>> ranges = new ArrayList<Range<Integer>>();

    for (int i = 0; i < tokens.size(); i++) {
        Range<Integer> range;
        String current = tokens.get(i);
        String next = i + 1 < tokens.size() ? tokens.get(i + 1) : null;

        // Yoda equality is done for null-safety
        if ("-".equals(current)) {
            throw new IllegalArgumentException("A hyphen must appear between two numbers.");
        } else if ("-".equals(next)) {
            if (i + 2 >= tokens.size())
                throw new IllegalArgumentException("Cannot form a range without a upper limit.");

            // This is a proper range
            range = Range.closed(Integer.parseInt(current), Integer.parseInt(tokens.get(i + 2)));
            ranges.add(range);

            // Skip the two next tokens
            i += 2;

        } else {
            // Just a single number
            range = Range.singleton(Integer.parseInt(current));
            ranges.add(range);
        }

        // Validate ranges
        if (!legalRange.encloses(range)) {
            throw new IllegalArgumentException(range + " is not in the range " + range.toString());
        }
    }

    return simplify(ranges, legalRange.upperEndpoint());
}

From source file:com.github.msdevkit.datamodel.impl.SpectrumImpl.java

SpectrumImpl(@Nonnull DataPointStoreImpl dataPointStore) {
    this.dataPointStore = dataPointStore;
    mzRange = Range.singleton(0d);
}

From source file:org.graylog2.commands.journal.JournalDecode.java

@Override
protected void runCommand() {

    Range<Long> range;//from  ww w . ja v a2  s  .c o m
    try {
        final List<String> offsets = Splitter.on("..").limit(2).splitToList(rangeArg);
        if (offsets.size() == 1) {
            range = Range.singleton(Long.valueOf(offsets.get(0)));
        } else if (offsets.size() == 2) {
            final String first = offsets.get(0);
            final String second = offsets.get(1);
            if (first.isEmpty()) {
                range = Range.atMost(Long.valueOf(second));
            } else if (second.isEmpty()) {
                range = Range.atLeast(Long.valueOf(first));
            } else {
                range = Range.closed(Long.valueOf(first), Long.valueOf(second));
            }
        } else {
            throw new RuntimeException();
        }
    } catch (Exception e) {
        System.err.println("Malformed offset range: " + rangeArg);
        return;
    }

    final Map<String, Codec.Factory<? extends Codec>> codecFactory = injector
            .getInstance(Key.get(new TypeLiteral<Map<String, Codec.Factory<? extends Codec>>>() {
            }));

    final Long readOffset = range.lowerEndpoint();
    final long count = range.upperEndpoint() - range.lowerEndpoint() + 1;
    final List<Journal.JournalReadEntry> entries = journal.read(readOffset, count);
    for (final Journal.JournalReadEntry entry : entries) {
        final RawMessage raw = RawMessage.decode(entry.getPayload(), entry.getOffset());
        if (raw == null) {
            System.err.println(
                    MessageFormatter.format("Journal entry at offset {} failed to decode", entry.getOffset()));
            continue;
        }

        final Codec codec = codecFactory.get(raw.getCodecName()).create(raw.getCodecConfig());
        final Message message = codec.decode(raw);
        if (message == null) {
            System.err.println(
                    MessageFormatter.format("Could not use codec {} to decode raw message id {} at offset {}",
                            new Object[] { raw.getCodecName(), raw.getId(), entry.getOffset() }));
        } else {
            message.setJournalOffset(raw.getJournalOffset());
        }

        final ResolvableInetSocketAddress remoteAddress = raw.getRemoteAddress();
        final String remote = remoteAddress == null ? "unknown address"
                : remoteAddress.getInetSocketAddress().toString();

        final StringBuffer sb = new StringBuffer();
        sb.append("Message ").append(raw.getId()).append('\n').append(" at ").append(raw.getTimestamp())
                .append('\n').append(" in format ").append(raw.getCodecName()).append('\n')
                .append(" at offset ").append(raw.getJournalOffset()).append('\n')
                .append(" received from remote address ").append(remote).append('\n').append(" (source field: ")
                .append(message == null ? "unparsed" : message.getSource()).append(')').append('\n');
        if (message != null) {
            sb.append(" contains ").append(message.getFieldNames().size()).append(" fields.");
        } else {
            sb.append("The message could not be parse by the given codec.");
        }
        System.out.println(sb);
    }

}

From source file:net.sf.mzmine.modules.visualization.infovisualizer.InfoVisualizerWindow.java

InfoVisualizerWindow(PeakList peakList) {

    super("Peak list information");

    // this.setTitle(peakList.getName() + " information");

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    // setBackground(Color.white);

    this.getInfoRange(peakList);

    if (peakList.getNumberOfRows() == 0) {
        mzRange = Range.singleton(0.0);
        rtRange = Range.singleton(0.0);//from w  w w .  j  a  va  2s . c  om
    }

    // Raw data file list
    JList<RawDataFile> rawDataFileList = new JList<RawDataFile>(peakList.getRawDataFiles());
    rawDataFileList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    rawDataFileList.setLayoutOrientation(JList.VERTICAL);
    JScrollPane rawlistScroller = new JScrollPane(rawDataFileList);
    rawlistScroller.setPreferredSize(new Dimension(250, 60));
    rawlistScroller.setAlignmentX(LEFT_ALIGNMENT);
    JPanel rawPanel = new JPanel();
    rawPanel.setLayout(new BoxLayout(rawPanel, BoxLayout.Y_AXIS));
    JLabel label = new JLabel("List of raw data files");
    // label.setLabelFor(rawDataFileList);
    rawPanel.add(label);
    rawPanel.add(rawlistScroller);
    rawPanel.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));

    // Applied methods list
    AppliedMethodList appliedMethodList = new AppliedMethodList(peakList.getAppliedMethods());
    appliedMethodList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    appliedMethodList.setLayoutOrientation(JList.VERTICAL);
    JScrollPane methodlistScroller = new JScrollPane(appliedMethodList);
    methodlistScroller.setPreferredSize(new Dimension(250, 80));
    methodlistScroller.setAlignmentX(LEFT_ALIGNMENT);

    JPanel methodPanel = new JPanel();
    methodPanel.setLayout(new BoxLayout(methodPanel, BoxLayout.Y_AXIS));
    // JLabel label = new JLabel("List of applied methods");
    // label.setLabelFor(processInfoList);
    methodPanel.add(new JLabel("List of applied methods"));
    methodPanel.add(methodlistScroller);
    methodPanel.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));

    // Panels
    JPanel pnlGrid = new JPanel();
    pnlGrid.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    c.fill = GridBagConstraints.HORIZONTAL;
    c.insets = new Insets(5, 5, 5, 5);
    c.gridwidth = 1;

    c.gridx = 0;
    c.gridy = 0;
    pnlGrid.add(new JLabel("<html>Name: <font color=\"blue\">" + peakList.getName() + "</font></html>"), c);
    c.gridx = 0;
    c.gridy = 1;
    pnlGrid.add(new JLabel("<html>Created (yyyy/MM/dd HH:mm:ss): <font color=\"blue\">"
            + ((SimplePeakList) peakList).getDateCreated() + "</font></html>"), c);
    c.gridx = 0;
    c.gridy = 2;
    pnlGrid.add(rawPanel, c);
    c.gridx = 0;
    c.gridy = 3;
    pnlGrid.add(new JLabel("<html>Number of rows: <font color=\"blue\">" + numOfRows + "</font></html>"), c);
    c.gridx = 0;
    c.gridy = 4;
    String text = mzFormat.format(mzRange.lowerEndpoint()) + " - " + mzFormat.format(mzRange.upperEndpoint());
    pnlGrid.add(new JLabel("<html>m/z range: <font color=\"blue\">" + text + "</font></html>"), c);
    c.gridx = 0;
    c.gridy = 5;
    text = rtFormat.format(rtRange.lowerEndpoint()) + " - " + rtFormat.format(rtRange.upperEndpoint());
    pnlGrid.add(new JLabel("<html>RT range: <font color=\"blue\">" + text + "</font> min</html>"), c);
    c.gridx = 0;
    c.gridy = 6;
    pnlGrid.add(new JLabel(
            "<html>Number of identified peaks: <font color=\"blue\">" + numOfIdentities + "</font></html>"), c);
    c.gridx = 0;
    c.gridy = 7;
    pnlGrid.add(methodPanel, c);

    add(pnlGrid);
    setResizable(false);

    // Add the Windows menu
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(new WindowsMenu());
    setJMenuBar(menuBar);

    pack();

    // get the window settings parameter
    ParameterSet paramSet = MZmineCore.getConfiguration().getModuleParameters(InfoVisualizerModule.class);
    WindowSettingsParameter settings = paramSet.getParameter(InfoVisualizerParameters.windowSettings);

    // update the window and listen for changes
    settings.applySettingsToWindow(this);
    this.addComponentListener(settings);

}

From source file:org.opendaylight.controller.cluster.datastore.FrontendClientMetadataBuilder.java

void onHistoryPurged(final LocalHistoryIdentifier historyId) {
    currentHistories.remove(historyId);/*w w  w . j  a  v  a 2s . com*/
    // XXX: do we need to account for cookies?
    purgedHistories.add(Range.singleton(UnsignedLong.fromLongBits(historyId.getHistoryId())));
}

From source file:io.github.mzmine.modules.plots.msspectrum.MsSpectrumPlotModule.java

@Override
public void runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters,
        @Nonnull Collection<Task<?>> tasks) {

    final RawDataFilesSelection fileSelection = parameters.getParameter(MsSpectrumPlotParameters.inputFiles)
            .getValue();//from   w  ww.  j  a va 2 s.  co m

    final Integer scanNumber = parameters.getParameter(MsSpectrumPlotParameters.scanNumber).getValue();

    Preconditions.checkNotNull(fileSelection);
    Preconditions.checkNotNull(scanNumber);

    final ScanSelection scanSelection = new ScanSelection(Range.singleton(scanNumber), null, null, null, null,
            null);

    final List<RawDataFile> dataFiles = fileSelection.getMatchingRawDataFiles();

    // Add the window to the desktop only if we actually have any raw
    // data to show.
    boolean weHaveData = false;
    for (RawDataFile dataFile : dataFiles) {
        if (!scanSelection.getMatchingScans(dataFile).isEmpty()) {
            weHaveData = true;
            break;
        }
    }
    if (!weHaveData) {
        MZmineGUI.displayMessage("Scan not found");
        return;
    }

    try {
        // Load the main window
        URL mainFXML = this.getClass().getResource(PLOT_FXML);
        FXMLLoader loader = new FXMLLoader(mainFXML);

        Parent node = loader.load();
        MZmineGUI.addWindow(node, "MS spectrum");
        MsSpectrumPlotWindowController controller = loader.getController();

        Platform.runLater(() -> {
            for (RawDataFile dataFile : dataFiles) {
                for (MsScan scan : scanSelection.getMatchingScans(dataFile)) {
                    String title = MsScanUtils.createSingleLineMsScanDescription(scan);
                    controller.addSpectrum(scan, title);
                }
            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:edu.kit.trufflehog.model.filter.IPAddressFilter.java

public IPAddressFilter(INetworkIOPort networkIOPort, final FilterInput filterInput) throws InvalidFilterRule {
    if (networkIOPort == null)
        throw new NullPointerException("networkIOPort must not be null!");

    if (filterInput == null)
        throw new NullPointerException("filterInput must not be null!");

    if (filterInput.getType() != FilterType.IP)
        throw new InvalidFilterRule(
                "The filter input contains invalid filter rules. This filter can only handle ip rules");

    this.networkIOPort = networkIOPort;
    filterColor = filterInput.getColor();
    priority = filterInput.getPriority();
    name = filterInput.getName();/*  w w w.  j  a  va2s. com*/

    final List<String> rules = filterInput.getRules();

    if (rules == null) {
        throw new NullPointerException("the rules list in filterInput must not be null!");
    }

    for (String rule : rules) {
        if (!rule.matches(
                "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\/(([1-2][0-9])|([1-9])|(3[0-2])))?$")) {
            throw new InvalidFilterRule("IP address doesn't have the correct format!");
        }

        if (rule.matches(
                "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")) {
            final String[] parts = rule.split("\\.");

            try {
                addresses.add(Range.singleton(new IPAddress(parseIP(parts))));
            } catch (InvalidIPAddress invalidIPAddress) {
                // nothing to do here because the ip address has to be valid due to the regex above.
            }
        } else {
            final String[] masks = rule.split("/");
            final String[] parts = masks[0].split("\\.");
            final long ip = parseIP(parts);
            final long subnetMaskCount = Integer.parseInt(masks[1]);

            final long deviceMask = (1 << (32 - subnetMaskCount)) - 1;
            final long subnetMask = ((long) ((1 << subnetMaskCount) - 1)) << (32 - subnetMaskCount);
            final long from = ip & subnetMask;
            final long to = ip | deviceMask;

            try {
                addresses.add(Range.closed(new IPAddress(from), new IPAddress(to)));
            } catch (InvalidIPAddress invalidIPAddress) {
                // this should never happen but just in case notify user
                invalidIPAddress.printStackTrace();
                throw new InvalidFilterRule(
                        "IP address doesn't have the correct format or a parsing error occurred!");
            }
        }
    }
}

From source file:guru.qas.martini.gherkin.DefaultMixology.java

protected List<Recipe> getRecipes(FeatureWrapper feature, Collection<Pickle> pickles) {
    Map<Integer, Recipe> recipeIndex = new LinkedHashMap<>();

    RangeMap<Integer, ScenarioDefinition> rangeMap = getRangeMap(feature);
    for (Pickle pickle : pickles) {
        List<PickleLocation> locations = pickle.getLocations();
        Map<Integer, PickleLocation> locationIndex = new HashMap<>();
        locations.forEach(l -> {/*from  w  w w. ja v a2s  .c o  m*/
            int line = l.getLine();
            locationIndex.put(line, l);
        });

        Integer line = Ordering.natural().max(locationIndex.keySet());
        recipeIndex.computeIfAbsent(line, l -> {
            PickleLocation location = locationIndex.get(l);
            Range<Integer> range = Range.singleton(line);
            RangeMap<Integer, ScenarioDefinition> subRangeMap = rangeMap.subRangeMap(range);
            Map<Range<Integer>, ScenarioDefinition> asMap = subRangeMap.asMapOfRanges();
            checkState(1 == asMap.size(), "no single range found encompassing PickleLocation %s", location);
            ScenarioDefinition definition = Iterables.getOnlyElement(asMap.values());
            return new DefaultRecipe(feature, pickle, location, definition);
        });
    }
    return ImmutableList.copyOf(recipeIndex.values());
}

From source file:org.pentaho.di.trans.steps.samplerows.SampleRows.java

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (SampleRowsMeta) smi;//  w  w  w  .j ava2s.  c o m
    data = (SampleRowsData) sdi;

    Object[] r = getRow(); // get row, set busy!
    if (r == null) { // no more input to be expected...

        setOutputDone();
        return false;
    }
    if (first) {
        first = false;

        String realRange = environmentSubstitute(meta.getLinesRange());
        data.addlineField = (!Utils.isEmpty(environmentSubstitute(meta.getLineNumberField())));

        // get the RowMeta
        data.previousRowMeta = getInputRowMeta().clone();
        data.NrPrevFields = data.previousRowMeta.size();
        data.outputRowMeta = data.previousRowMeta;
        if (data.addlineField) {
            meta.getFields(data.outputRowMeta, getStepname(), null, null, this, repository, metaStore);
        }

        String[] rangePart = realRange.split(",");
        ImmutableRangeSet.Builder<Integer> setBuilder = ImmutableRangeSet.builder();

        for (String part : rangePart) {
            if (part.matches("\\d+")) {
                if (log.isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "SampleRows.Log.RangeValue", part));
                }
                int vpart = Integer.valueOf(part);
                setBuilder.add(Range.singleton(vpart));

            } else if (part.matches("\\d+\\.\\.\\d+")) {
                String[] rangeMultiPart = part.split("\\.\\.");
                Integer start = Integer.valueOf(rangeMultiPart[0]);
                Integer end = Integer.valueOf(rangeMultiPart[1]);
                Range<Integer> range = Range.closed(start, end);
                if (log.isDebug()) {
                    logDebug(BaseMessages.getString(PKG, "SampleRows.Log.RangeValue", range));
                }
                setBuilder.add(range);
            }
        }
        data.rangeSet = setBuilder.build();
    } // end if first

    if (data.addlineField) {
        data.outputRow = RowDataUtil.allocateRowData(data.outputRowMeta.size());
        for (int i = 0; i < data.NrPrevFields; i++) {
            data.outputRow[i] = r[i];
        }
    } else {
        data.outputRow = r;
    }

    int linesRead = (int) getLinesRead();
    if (data.rangeSet.contains(linesRead)) {
        if (data.addlineField) {
            data.outputRow[data.NrPrevFields] = getLinesRead();
        }

        // copy row to possible alternate rowset(s).
        //
        putRow(data.outputRowMeta, data.outputRow);

        if (log.isRowLevel()) {
            logRowlevel(BaseMessages.getString(PKG, "SampleRows.Log.LineNumber",
                    linesRead + " : " + getInputRowMeta().getString(r)));
        }
    }

    // Check if maximum value has been exceeded
    if (data.rangeSet.isEmpty() || linesRead >= data.rangeSet.span().upperEndpoint()) {
        setOutputDone();
    }

    // Allowed to continue to read in data
    return true;
}

From source file:com.wandrell.tabletop.interval.util.IntervalArithmeticsUtils.java

/**
 * Indicates if an interval contains a value.
 * // w ww . j  a va2 s.  com
 * @param interval
 *            the interval for the check
 * @param value
 *            the value to check
 * @return {@code true} if the value is contained, {@code false} otherwise
 */
public static final Boolean isContaining(final Interval interval, final Integer value) {
    final Range<Integer> rangeA;
    final Range<Integer> rangeB;

    checkNotNull(interval, "Received a null pointer as interval");
    checkNotNull(value, "Received a null pointer as value");

    checkArgument(isValid(interval), "Received an invalid interval");

    rangeA = Range.closed(interval.getLowerLimit(), interval.getUpperLimit());
    rangeB = Range.singleton(value);

    return rangeA.encloses(rangeB);
}