Example usage for org.apache.commons.lang3.tuple ImmutablePair ImmutablePair

List of usage examples for org.apache.commons.lang3.tuple ImmutablePair ImmutablePair

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple ImmutablePair ImmutablePair.

Prototype

public ImmutablePair(final L left, final R right) 

Source Link

Document

Create a new pair instance.

Usage

From source file:com.pinterest.terrapin.zookeeper.ZooKeeperManager.java

/**
 * Returns a mapping of all file sets and their file set info(s) including the ones stored
 * as part of locks./*from w w w  .j  a va  2 s . c  o m*/
 */
public Map<String, Pair<FileSetInfo, FileSetInfo>> getCandidateHdfsDirMap()
        throws ZooKeeperClient.ZooKeeperConnectionException, KeeperException, InterruptedException {
    Map<String, Pair<FileSetInfo, FileSetInfo>> map = Maps.newHashMapWithExpectedSize(fileSetInfoMap.size());
    for (String fileSet : fileSetInfoMap.keySet()) {
        FileSetInfo currentFileSetInfo = null;
        FileSetInfo lockedFileSetInfo = null;
        // We do a forced zookeeper read to avoid any delays in propagation of watches.
        // This API is only used by the controller inside a single thread, so it should
        // not be heavy on zookeeper.
        try {
            currentFileSetInfo = getFileSetInfoForced(fileSet);
        } catch (KeeperException e) {
            // If we get an exception other than NoNodeException, simply rethrow.
            if (!(e instanceof KeeperException.NoNodeException)) {
                throw e;
            }
        }
        try {
            lockedFileSetInfo = getLockedFileSetInfo(fileSet);
        } catch (KeeperException e) {
            // If we get an exception other than NoNodeException, simply rethrow.
            if (!(e instanceof KeeperException.NoNodeException)) {
                throw e;
            }
        }
        if (currentFileSetInfo != null && !currentFileSetInfo.valid) {
            currentFileSetInfo = null;
        }
        if (lockedFileSetInfo != null || currentFileSetInfo != null) {
            map.put(fileSet, new ImmutablePair(currentFileSetInfo, lockedFileSetInfo));
        }
    }
    return map;
}

From source file:com.artistech.protobuf.TuioProtoConverter.java

@Override
public ArrayList<ImmutablePair<String, String>> supportedConversions() {
    ArrayList<ImmutablePair<String, String>> ret = new ArrayList<>();
    ret.add(new ImmutablePair<>(com.artistech.protobuf.TuioProtos.Object.class.getName(),
            TUIO.TuioObject.class.getName()));
    ret.add(new ImmutablePair<>(com.artistech.protobuf.TuioProtos.Cursor.class.getName(),
            TUIO.TuioCursor.class.getName()));
    ret.add(new ImmutablePair<>(com.artistech.protobuf.TuioProtos.Blob.class.getName(),
            TUIO.TuioBlob.class.getName()));
    ret.add(new ImmutablePair<>(com.artistech.protobuf.TuioProtos.Time.class.getName(),
            TUIO.TuioTime.class.getName()));
    ret.add(new ImmutablePair<>(com.artistech.protobuf.TuioProtos.Point.class.getName(),
            TUIO.TuioPoint.class.getName()));
    return ret;/* w  w  w. j  a v  a 2s  .  com*/
}

From source file:io.pravega.controller.server.eventProcessor.ControllerEventProcessors.java

private CompletableFuture<Void> handleOrphanedReaders(
        final EventProcessorGroup<? extends ControllerEvent> group, final Supplier<Set<String>> processes) {
    return withRetriesAsync(() -> CompletableFuture.supplyAsync(() -> {
        try {// w  w  w.j  av  a 2s.  c  o m
            return group.getProcesses();
        } catch (CheckpointStoreException e) {
            if (e.getType().equals(CheckpointStoreException.Type.NoNode)) {
                return Collections.<String>emptySet();
            }
            throw new CompletionException(e);
        }
    }, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor)
            .thenComposeAsync(groupProcesses -> withRetriesAsync(() -> CompletableFuture.supplyAsync(() -> {
                try {
                    return new ImmutablePair<>(processes.get(), groupProcesses);
                } catch (Exception e) {
                    log.error(String.format("Error fetching current processes%s", group.toString()), e);
                    throw new CompletionException(e);
                }
            }, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor)).thenComposeAsync(pair -> {
                Set<String> activeProcesses = pair.getLeft();
                Set<String> registeredProcesses = pair.getRight();

                if (registeredProcesses == null || registeredProcesses.isEmpty()) {
                    return CompletableFuture.completedFuture(null);
                }

                if (activeProcesses != null) {
                    registeredProcesses.removeAll(activeProcesses);
                }

                List<CompletableFuture<Void>> futureList = new ArrayList<>();
                for (String process : registeredProcesses) {
                    futureList.add(withRetriesAsync(() -> CompletableFuture.runAsync(() -> {
                        try {
                            group.notifyProcessFailure(process);
                        } catch (CheckpointStoreException e) {
                            log.error(String.format(
                                    "Error notifying failure of process=%s in event processor group %s",
                                    process, group.toString()), e);
                            throw new CompletionException(e);
                        }
                    }, executor), RETRYABLE_PREDICATE, Integer.MAX_VALUE, executor));
                }

                return FutureHelpers.allOf(futureList);
            });
}

From source file:fredboat.audio.player.GuildPlayer.java

public Pair<Boolean, String> canMemberSkipTracks(Member member, Collection<Long> trackIds) {
    if (PermsUtil.checkPerms(PermissionLevel.DJ, member)) {
        return new ImmutablePair<>(true, null);
    } else {//from  ww  w  . j ava2  s  .  c  o  m
        //We are not a mod
        long userId = member.getUser().getIdLong();

        //if there is a currently playing track, and the track is requested to be skipped, but not owned by the
        // requesting user, then currentTrackSkippable should be false
        boolean currentTrackSkippable = true;
        AudioTrackContext playingTrack = getPlayingTrack();
        if (playingTrack != null && trackIds.contains(getPlayingTrack().getTrackId())
                && playingTrack.getUserId() != userId) {

            currentTrackSkippable = false;
        }

        if (currentTrackSkippable && audioTrackProvider.isUserTrackOwner(userId, trackIds)) { //check ownership of the queued tracks
            return new ImmutablePair<>(true, null);
        } else {
            return new ImmutablePair<>(false, I18n.get(getGuild()).getString("skipDeniedTooManyTracks"));
        }
    }
}

From source file:com.offbynull.peernetic.debug.visualizer.JGraphXVisualizer.java

private void removeConnection(final RemoveEdgeCommand<A> command) {
    Validate.notNull(command);/* w w  w .  j  a v a 2  s  .  c  o m*/

    SwingUtilities.invokeLater(() -> {
        Object fromVertex = nodeLookupMap.get(command.getFrom());
        Object toVertex = nodeLookupMap.get(command.getTo());
        ImmutablePair<A, A> conn = new ImmutablePair<>(command.getFrom(), command.getTo());
        Validate.isTrue(nodeLookupMap.containsKey(command.getFrom()), "Connection %s source doesn't exist",
                conn);
        Validate.isTrue(nodeLookupMap.containsKey(command.getTo()), "Connection %s destination doesn't exist",
                conn);
        Validate.isTrue(connToEdgeLookupMap.containsKey(conn), "Connection %s doesn't exists", conn);

        if (fromVertex == null || toVertex == null) {
            return;
        }

        Collection<Object> edges = (Collection<Object>) connToEdgeLookupMap.get(conn);
        Object edge = edges.iterator().next();

        connToEdgeLookupMap.removeMapping(conn, edge);
        edgeToConnLookupMap.remove(edge);

        graph.getModel().remove(edge);

        triggerIfNoEdges(command.getFrom(), fromVertex);
        triggerIfNoEdges(command.getTo(), toVertex);

        zoomFit();
    });
}

From source file:com.streamsets.pipeline.stage.it.DriftIT.java

@Test
public void testDifferentColumnCase() throws Exception {
    HiveMetadataProcessor processor = new HiveMetadataProcessorBuilder().build();
    HiveMetastoreTarget hiveTarget = new HiveMetastoreTargetBuilder().build();
    List<Record> records = new LinkedList<>();

    Map<String, Field> map = new LinkedHashMap<>();
    map.put("ID", Field.create(Field.Type.INTEGER, 1));
    Record record = RecordCreator.create("s", "s:1");
    record.set(Field.create(map));
    records.add(record);//from  w ww  .j  a v a2 s  .c o m
    processRecords(processor, hiveTarget, records);

    assertQueryResult("select * from tbl order by id", new QueryValidator() {
        @Override
        public void validateResultSet(ResultSet rs) throws Exception {
            assertResultSetStructure(rs, new ImmutablePair("tbl.id", Types.INTEGER),
                    new ImmutablePair("tbl.dt", Types.VARCHAR));

            Assert.assertTrue("Table tbl doesn't contain any rows", rs.next());
            Assert.assertEquals(1, rs.getInt(1));
            Assert.assertFalse("Unexpected number of rows", rs.next());
        }
    });
}

From source file:com.linkedin.pinot.common.utils.MmapUtils.java

/**
 * Obtains the list of all allocations and their associated sizes. Only meant for debugging purposes.
 *///from  ww w  .j  ava  2s  .  c o  m
public static List<Pair<AllocationContext, Integer>> getAllocationsAndSizes() {
    List<Pair<AllocationContext, Integer>> returnValue = new ArrayList<Pair<AllocationContext, Integer>>();

    synchronized (BUFFER_TO_CONTEXT_MAP) {
        clearSynchronizedMapEntrySetCache();

        Set<Map.Entry<ByteBuffer, AllocationContext>> entries = BUFFER_TO_CONTEXT_MAP.entrySet();

        // Clear the entry set cache afterwards so that we don't hang on to stale entries
        clearSynchronizedMapEntrySetCache();

        for (Map.Entry<ByteBuffer, AllocationContext> bufferAndContext : entries) {
            returnValue.add(new ImmutablePair<AllocationContext, Integer>(bufferAndContext.getValue(),
                    bufferAndContext.getKey().capacity()));
        }
    }

    return returnValue;
}

From source file:com.epam.catgenome.manager.gene.GeneRegisterer.java

private void addToMetamapAndHistogram(Map<String, Pair<Integer, Integer>> metaMap,
        Map<String, Chromosome> chromosomeMap, GeneFeature feature, int featuresCount, GeneFile geneFile)
        throws IOException {
    if (currentChromosome != null) {
        metaMap.put(currentChromosome.getName(), new ImmutablePair<>(startPosition, endPosition));
        currentWig.setValue((float) featuresCount);
        histogram.add(currentWig);/*from w w  w. jav  a2s. c  o m*/
        fileManager.writeHistogram(geneFile, currentChromosome.getName(), histogram);
        histogram.clear();
    }

    startPosition = feature.getStart();
    currentKey = feature.getContig();

    currentChromosome = chromosomeMap.containsKey(currentKey) ? chromosomeMap.get(currentKey)
            : chromosomeMap.get(Utils.changeChromosomeName(currentKey));
    // calculate histogram blocks size for next chromosome
    if (currentChromosome != null) {
        histogramSize = Math.min((int) Math.ceil(currentChromosome.getSize() * HISTOGAM_BLOCK_SIZE_PART),
                HISTOGAM_SIZE_LIMIT);
        intervalLength = currentChromosome.getSize() / histogramSize;
        intervalEnd = intervalLength;
        currentWig = new Wig(1, intervalEnd);
    } else {
        currentWig = null;
    }
}

From source file:com.telefonica.iot.cygnus.backends.http.HttpBackend.java

/**
 * Finishes a transaction. Basically, this means the the bytes counters are
 * retrieved./*from  w  w  w.  j  ava 2  s. c  o m*/
 * 
 * @return
 */
public ImmutablePair<Long, Long> finishTransaction() {
    return new ImmutablePair<Long, Long>(transactionRequestBytes, transactionResponseBytes);
}

From source file:com.github.aptd.simulation.datamodel.CXMLReader.java

/**
 * create the train list// ww w.  j  a va 2 s.  co m
 *
 * @param p_network network component
 * @param p_agents map with agent asl scripts
 * @param p_factory factory
 * @return unmodifiable map with trains
 */
private static Pair<Map<String, ITrain<?>>, Map<String, IDoor<?>>> train(final Network p_network,
        final Map<String, String> p_agents, final IFactory p_factory, final ITime p_time,
        final double p_minfreetimetoclose) {
    final String l_dooragent = IStatefulElement.getDefaultAsl("door");
    final Map<String, IElement.IGenerator<ITrain<?>>> l_generators = new ConcurrentHashMap<>();
    final Set<IAction> l_actions = CCommon.actionsFromPackage().collect(Collectors.toSet());
    final IElement.IGenerator<IDoor<?>> l_doorgenerator = doorgenerator(p_factory, l_dooragent, l_actions,
            p_time);
    final Map<String, AtomicLong> l_doorcount = Collections.synchronizedMap(new HashMap<>());
    final Map<String, IDoor<?>> l_doors = Collections.synchronizedMap(new HashMap<>());
    return new ImmutablePair<>(
            Collections.<String, ITrain<?>>unmodifiableMap(
                    p_network.getTimetable().getTrains().getTrain().parallelStream()
                            .filter(i -> hasagentname(i.getAny3())).map(i -> agentname(i, i.getAny3()))
                            .map(i -> l_generators
                                    .computeIfAbsent(i.getRight(),
                                            a -> traingenerator(p_factory, p_agents.get(i.getRight()),
                                                    l_actions, p_time))
                                    .generatesingle(i.getLeft().getId(),
                                            i.getLeft().getTrainPartSequence().stream().flatMap(ref -> {
                                                // @todo support multiple train parts
                                                final EOcpTT[] l_tts = ((ETrainPart) ref.getTrainPartRef()
                                                        .get(0).getRef()).getOcpsTT().getOcpTT()
                                                                .toArray(new EOcpTT[0]);
                                                final CTrain.CTimetableEntry[] l_entries = new CTrain.CTimetableEntry[l_tts.length];
                                                for (int j = 0; j < l_tts.length; j++) {
                                                    final EArrivalDepartureTimes l_times = l_tts[j].getTimes()
                                                            .stream()
                                                            .filter(t -> t.getScope()
                                                                    .equalsIgnoreCase("published"))
                                                            .findAny().orElseThrow(() -> new CSemanticException(
                                                                    "missing published times"));
                                                    l_entries[j] = new CTrain.CTimetableEntry(
                                                            j < 1 ? 0.0
                                                                    : ((ETrack) l_tts[j - 1].getSectionTT()
                                                                            .getTrackRef().get(0).getRef())
                                                                                    .getTrackTopology()
                                                                                    .getTrackEnd().getPos()
                                                                                    .doubleValue(),
                                                            ((EOcp) l_tts[j].getOcpRef()).getId(),
                                                            l_tts[j].getStopDescription().getOtherAttributes()
                                                                    .getOrDefault(PLATFORM_REF_ATTRIBUTE, null),
                                                            l_times.getArrival() == null ? null
                                                                    : l_times.getArrival().toGregorianCalendar()
                                                                            .toZonedDateTime()
                                                                            .with(LocalDate.from(p_time
                                                                                    .current()
                                                                                    .atZone(ZoneId
                                                                                            .systemDefault())))
                                                                            .toInstant(),
                                                            l_times.getDeparture() == null ? null
                                                                    : l_times.getDeparture()
                                                                            .toGregorianCalendar()
                                                                            .toZonedDateTime()
                                                                            .with(LocalDate.from(p_time
                                                                                    .current()
                                                                                    .atZone(ZoneId
                                                                                            .systemDefault())))
                                                                            .toInstant());
                                                }
                                                return Arrays.stream(l_entries);
                                            }), i.getLeft().getTrainPartSequence().stream()
                                                    // @todo support multiple train parts
                                                    .map(s -> (ETrainPart) s.getTrainPartRef().get(0).getRef())
                                                    .map(p -> (EFormation) p.getFormationTT().getFormationRef())
                                                    .flatMap(f -> f.getTrainOrder().getVehicleRef().stream())
                                                    .map(r -> new ImmutablePair<BigInteger, TDoors>(
                                                            r.getVehicleCount(),
                                                            ((EVehicle) r.getVehicleRef()).getWagon()
                                                                    .getPassenger().getDoors()))
                                                    .flatMap(v -> IntStream
                                                            .range(0,
                                                                    v.getLeft().intValue() * v.getRight()
                                                                            .getNumber().intValue())
                                                            .mapToObj(j -> l_doors.computeIfAbsent("door-"
                                                                    + i.getLeft().getId() + "-"
                                                                    + l_doorcount
                                                                            .computeIfAbsent(i.getLeft()
                                                                                    .getId(),
                                                                                    id -> new AtomicLong(1L))
                                                                            .getAndIncrement(),
                                                                    id -> l_doorgenerator.generatesingle(id,
                                                                            i.getLeft().getId(),
                                                                            v.getRight().getEntranceWidth()
                                                                                    .doubleValue()
                                                                                    / v.getRight().getNumber()
                                                                                            .longValue(),
                                                                            p_minfreetimetoclose))))
                                                    .collect(Collectors.toList())))
                            .collect(Collectors.toMap(IElement::id, i -> i))),
            l_doors);
}