Java 类org.apache.commons.lang3.tuple.ImmutablePair 实例源码

项目:pnc-repressurized    文件:AirHandler.java   
/**
 * Retrieves a list of all the connecting pneumatics. It takes sides in account.
 *
 * @return a list of face->air-handler pairs
 */
@Override
public List<Pair<EnumFacing, IAirHandler>> getConnectedPneumatics() {
    List<Pair<EnumFacing, IAirHandler>> teList = new ArrayList<>();
    for (IAirHandler specialConnection : specialConnectedHandlers) {
        teList.add(new ImmutablePair<>(null, specialConnection));
    }
    for (EnumFacing direction : EnumFacing.VALUES) {
        TileEntity te = getTileCache()[direction.ordinal()].getTileEntity();
        IPneumaticMachine machine = ModInteractionUtils.getInstance().getMachine(te);
        if (machine != null && parentPneumatic.getAirHandler(direction) == this && machine.getAirHandler(direction.getOpposite()) != null) {
            teList.add(new ImmutablePair<>(direction, machine.getAirHandler(direction.getOpposite())));
        }
    }
    if (airListener != null) airListener.addConnectedPneumatics(teList);
    return teList;
}
项目:kubernetes-HDFS    文件:PodCIDRToNodeMapping.java   
String findNodeByPodIP(String podIP) {
  for (ImmutablePair<Netmask, ImmutableMap<NetworkAddress, String>> entry : podSubnetToNode) {
    Netmask netmask = entry.getLeft();
    ImmutableMap<NetworkAddress, String> networkToNode = entry.getRight();
    // Computes the subnet that results from the netmask applied to the pod IP.
    SubnetInfo podSubnetToCheck;
    try {
      podSubnetToCheck = new SubnetUtils(podIP, netmask.getValue()).getInfo();
    } catch (IllegalArgumentException e) {
      log.warn(e);
      continue;
    }
    String networkAddress = podSubnetToCheck.getNetworkAddress();
    String nodeName = networkToNode.get(new NetworkAddress(networkAddress));
    if (nodeName != null) {  // The cluster node is in charge of this pod IP subnet.
      return nodeName;
    }
  }
  return "";
}
项目:dremio-oss    文件:OperatorWrapper.java   
public String getContent() {
  TableBuilder builder = new TableBuilder(OPERATOR_COLUMNS);

  for (ImmutablePair<OperatorProfile, Integer> ip : ops) {
    int minor = ip.getRight();
    OperatorProfile op = ip.getLeft();

    String path = new OperatorPathBuilder().setMajor(major).setMinor(minor).setOperator(op).build();
    builder.appendCell(path, null);
    builder.appendNanos(op.getSetupNanos());
    builder.appendNanos(op.getProcessNanos());
    builder.appendNanos(op.getWaitNanos());

    long maxBatches = Long.MIN_VALUE;
    long maxRecords = Long.MIN_VALUE;
    for (StreamProfile sp : op.getInputProfileList()) {
      maxBatches = Math.max(sp.getBatches(), maxBatches);
      maxRecords = Math.max(sp.getRecords(), maxRecords);
    }

    builder.appendFormattedInteger(maxBatches, null);
    builder.appendFormattedInteger(maxRecords, null);
    builder.appendBytes(op.getPeakLocalMemoryAllocated(), null);
  }
  return builder.build();
}
项目:Catan    文件:SessionController.java   
/**
 * Builds a city wall around city at given coordinatepair
 *
 * @precondition the coordinatepair wallPosition has a city of given player color on it
 */
public boolean buildCityWall(PlayerColor owner, CoordinatePair wallPosition, boolean fromPeer) {
    Player currentP = aSessionManager.getPlayerFromColor(owner);
    aGameBoardManager.buildCityWall(currentP, wallPosition);

    // update gui
    aSessionScreen.putCityWall(wallPosition, owner);

    if (!fromPeer) {
        // send message to network about change 
        CityWallChange request = CityWallChange.newInstance(true, new ImmutablePair<Integer, Integer>(wallPosition.getLeft(), wallPosition.getRight()), owner, localPlayer.getUsername());
        CatanGame.client.sendTCP(request);

        // remove resources it cost to build the city wall
        aTransactionManager.payPlayerToBank(currentP, GameRules.getGameRulesInstance().getCityWallCost(aSessionManager.getCurrentlyExecutingProgressCard()));
        aSessionScreen.updateResourceBar(localPlayer.getResources());
    }

    return true;
}
项目:Catan    文件:SessionController.java   
/**
 * Requests the GameBoardManager to move the robber to given location. If fromPeer is false, the SessionController sends message to network notifying
 * other peers about board change
 */
public boolean moveRobber(Hex newPosition, boolean fromPeer) {
    if (newPosition == null) {
        newPosition = Hex.newInstance(CoordinatePair.of(-30, -30, HarbourKind.NONE), TerrainKind.SEA, 0);
        aGameBoardManager.setRobberPosition(null);
        aSessionScreen.placeRobber(-30, -30);
    } else {
        aGameBoardManager.setRobberPosition(newPosition);
        aSessionScreen.placeRobber(newPosition.getLeftCoordinate(), newPosition.getRightCoordinate());
    }
    if (!fromPeer) {
        MoveRobberRequest request;
        if (newPosition == null) {
            request = MoveRobberRequest.newInstance(new ImmutablePair<Integer, Integer>(newPosition.getLeftCoordinate(), newPosition.getRightCoordinate()), localPlayer.getUsername(), true);
        } else {
            request = MoveRobberRequest.newInstance(new ImmutablePair<Integer, Integer>(newPosition.getLeftCoordinate(), newPosition.getRightCoordinate()), localPlayer.getUsername(), false);
        }
        CatanGame.client.sendTCP(request);
    }

    return true;
}
项目:Catan    文件:SessionController.java   
public boolean movePirate(Hex newPosition, boolean fromPeer) { // TODO finish changes
    if (newPosition == null) {
        newPosition = Hex.newInstance(CoordinatePair.of(-30, -30, HarbourKind.NONE), TerrainKind.SEA, 0);
        aGameBoardManager.setPiratePosition(null);
        aSessionScreen.placePirate(-30, -30);
    } else {
        aGameBoardManager.setPiratePosition(newPosition);
        aSessionScreen.placePirate(newPosition.getLeftCoordinate(), newPosition.getRightCoordinate());
    }
    if (!fromPeer) {
        MovePirateRequest request;
        if(newPosition == null) {
            request = MovePirateRequest.newInstance(new ImmutablePair<Integer, Integer>(newPosition.getLeftCoordinate(), newPosition.getRightCoordinate()), localPlayer.getUsername(), true);
        } else {
            request = MovePirateRequest.newInstance(new ImmutablePair<Integer, Integer>(newPosition.getLeftCoordinate(), newPosition.getRightCoordinate()), localPlayer.getUsername(), false);
        }
        CatanGame.client.sendTCP(request);
    }

    return true;
}
项目:Catan    文件:SessionController.java   
/**
 * Requests the GameBoardManager to move the merchant to given position. If fromPeer is false, SessionController sends a message to the network notifying
 * other peers of board change.
 *
 * @param newPosition new merchant position
 * @param newOwner    player who now owns the merchant
 * @param fromPeer    indicates whether method was called from localPlayer or peer
 */
public boolean moveMerchant(Hex newPosition, PlayerColor newOwner, boolean fromPeer) {
    Player owner = aSessionManager.getPlayerFromColor(newOwner);

    aGameBoardManager.setMerchantOwner(owner);
    aGameBoardManager.setMerchantPosition(newPosition);
    aSessionScreen.placeMerchant(newPosition.getLeftCoordinate(), newPosition.getRightCoordinate());

    if (!fromPeer) {
        MoveMerchantRequest request = MoveMerchantRequest.newInstance(new ImmutablePair<Integer, Integer>(newPosition.getLeftCoordinate(), newPosition.getRightCoordinate()), newOwner, localPlayer.getUsername());
        CatanGame.client.sendTCP(request);
    }

    CatanGame.client.sendTCP(UpdateVP.newInstance(localPlayer.getUsername()));

    return true;
}
项目:information-retrieval    文件:CorpusReader.java   
/**
 * Parses all document present in the referenced file path
 *
 * @param stringsQueue to parse
 * @return list with all documents with it's content in untokenized/unstemmed raw keywords
 */
public List<Document> parse(ConcurrentLinkedQueue<String> stringsQueue) {

    //compile our corpus regex so we can apply it on our parsing process
    Pattern id_content = Pattern.compile(CORPUS_REGEX_DOCUMENT);

    //parsing process
    return stringsQueue.parallelStream()
            .filter(line -> !line.isEmpty()) // line is not empty
            .map(id_content::matcher)// regex it
            .filter(Matcher::find) // did we regex anything? if so create document
            .map(match ->
            {
                //get the corpusID for this new file that we processing
                int corpusID = corpusCount.getAndIncrement();

                //map the corpusID to its corresponding filepath
                corpusIDToPath.computeIfAbsent(corpusID, v -> new ImmutablePair<>(match.group(4), Integer.parseInt(match.group(1))));
                return new Document(
                        corpusID, //first match is doc id and used to create our own doc id
                        Arrays.asList(match.group(5).split(" ")).parallelStream() // split document content in words
                                .collect(Collectors.toList())); // and put them in a list
            })
            .collect(Collectors.toList()); //collect all parsed lines
}
项目:sponge    文件:DecomposedQueueMainProcessingUnit.java   
/**
 * Processes an event. Adds a decomposed entry (trigger adapter or event set processor group adapter, event) to the decomposed queue.
 *
 * @param event an event.
 *
 * @return {@code true} if the event hasn't been processed by any adapters and should be put into the Output Queue.
 * @throws java.lang.InterruptedException if interrupted.
 */
public boolean processEvent(Event event) throws InterruptedException {
    if (event instanceof ControlEvent) {
        if (event instanceof ProcessorControlEvent) {
            ProcessorAdapter<?> processorAdapter = ((ProcessorControlEvent) event).getProcessorAdapter();
            if (processorAdapter instanceof EventProcessorAdapter && supportsControlEventForProcessor(processorAdapter)) {
                putIntoDecomposedQueue(new ImmutablePair<>((EventProcessorAdapter<?>) processorAdapter, event));
            }
        }

        return false;
    } else {
        getEngine().getStatisticsManager().startTimeMeasurementIfNotStartedYet();

        Set<AtomicReference<EventProcessorAdapter<?>>> adapterRs = getEventProcessors(event.getName());
        for (AtomicReference<EventProcessorAdapter<?>> adapterR : adapterRs) {
            putIntoDecomposedQueue(new ImmutablePair<>(adapterR.get(), event));
        }

        getEngine().getStatisticsManager().incrementTimeMeasurementEventCount();

        return adapterRs.isEmpty();
    }
}
项目:sponge    文件:DefaultConfigurationManager.java   
protected Pair<XMLConfiguration, URL> createXmlConfiguration(String fileName) {
    List<Lookup> lookups = Arrays.asList(new SystemPropertiesLookup(), new HomeLookup(), new ConfigLookup());

    Parameters params = new Parameters();
    FallbackBasePathLocationStrategy locationStrategy =
            new FallbackBasePathLocationStrategy(FileLocatorUtils.DEFAULT_LOCATION_STRATEGY, home);
    FileBasedConfigurationBuilder<XMLConfiguration> builder = new FileBasedConfigurationBuilder<>(XMLConfiguration.class)
            .configure(params.xml().setDefaultLookups(lookups).setLocationStrategy(locationStrategy).setFileName(fileName)
                    .setSchemaValidation(true).setEntityResolver(new ResourceSchemaResolver()));

    try {
        XMLConfiguration xmlConfiguration = builder.getConfiguration();

        return new ImmutablePair<>(xmlConfiguration, locationStrategy.getLocatedUrl());
    } catch (ConfigurationException e) {
        throw new ConfigException(e);
    }
}
项目:sponge    文件:BaseKnowledgeBaseInterpreter.java   
/**
 * Resolves event specification "&lt;name&gt; &lt;alias&gt; : &lt;mode&gt;". Uses default value when one not provided.
 *
 * @param eventSpecString event specification.
 * @return rule event specification, i.e. a triple of (name, alias, mode).
 */
protected RuleEventSpec getCustomRuleEventSpec(String eventSpecString) {
    if (eventSpecString == null) {
        throw new SpongeException("Event specification is null");
    }

    List<String> mainList =
            Arrays.stream(eventSpecString.split(":")).map(s -> s.trim()).filter(s -> !s.isEmpty()).collect(Collectors.toList());
    if (mainList.isEmpty()) {
        throw new SpongeException("Event specification is empty");
    } else if (mainList.size() > 2) {
        throw new SpongeException("Event specification has too many elements separated by ':'");
    }

    ImmutablePair<String, String> nameAlias = resolveEventNameAndAlias(mainList.get(0));
    EventMode eventMode = RuleAdapter.DEFAULT_MODE;
    if (mainList.size() == 2) {
        try {
            eventMode = EventMode.valueOf(mainList.get(1).toUpperCase());
        } catch (Exception e) {
            throw new SpongeException("Event mode is incorrect: " + mainList.get(1));
        }
    }

    return new GenericRuleEventSpec(nameAlias.getLeft(), nameAlias.getRight(), eventMode);
}
项目:sponge    文件:BaseKnowledgeBaseInterpreter.java   
protected ImmutablePair<String, String> resolveEventNameAndAlias(String eventSpecString) {
    if (eventSpecString == null) {
        throw new SpongeException("Event specification is null");
    }

    if (eventSpecString.trim().length() < 1) {
        throw new SpongeException("Event specification is empty");
    }

    StringTokenizer st = new StringTokenizer(eventSpecString, " \t\n\r\f", false);

    String eventName = st.nextToken();
    String eventAlias = st.hasMoreTokens() ? st.nextToken() : eventName;

    return new ImmutablePair<>(eventName, eventAlias);
}
项目:saluki    文件:ConsulRegistry.java   
@Override
protected synchronized void doSubscribe(GrpcURL url,
    NotifyListener.NotifyServiceListener listener) {
  Pair<GrpcURL, Set<NotifyListener.NotifyServiceListener>> listenersPair =
      notifyServiceListeners.get(url.getServiceKey());
  if (listenersPair == null) {
    Set<NotifyListener.NotifyServiceListener> listeners = Sets.newConcurrentHashSet();
    listeners.add(listener);
    listenersPair =
        new ImmutablePair<GrpcURL, Set<NotifyListener.NotifyServiceListener>>(url, listeners);
  } else {
    listenersPair.getValue().add(listener);
  }
  notifyServiceListeners.putIfAbsent(url.getServiceKey(), listenersPair);
  if (!serviceGroupLookUped.contains(url.getGroup())) {
    serviceGroupLookUped.add(url.getGroup());
    ServiceLookUper serviceLookUper = new ServiceLookUper(url.getGroup());
    serviceLookUper.setDaemon(true);
    serviceLookUper.start();
    ConsulEphemralNode ephemralNode = this.buildEphemralNode(url, ThrallRoleType.CONSUMER);
    client.registerEphemralNode(ephemralNode);
  } else {
    notifyListener(url, listener);
  }
}
项目:saluki    文件:CommonProto2Java.java   
private Pair<String, String> packageClassName(FileOptions options) {
  String packageName = null;
  String className = null;
  for (Map.Entry<FieldDescriptor, Object> entry : options.getAllFields().entrySet()) {
    if (entry.getKey().getName().equals("java_package")) {
      packageName = entry.getValue().toString();
    }
    if (entry.getKey().getName().equals("java_outer_classname")) {
      className = entry.getValue().toString();
    }
  }
  if (packageName != null && className != null) {
    return new ImmutablePair<String, String>(packageName, className);
  }
  return null;
}
项目:saluki    文件:TestController.java   
private Pair<String, String> getAnnotation(String className) throws ClassNotFoundException {
  Class<?> beanType = ReflectUtils.name2class(className);
  Map<String, ?> beanMap = applicationContext.getBeansOfType(beanType);
  String group = null;
  String version = null;
  for (Map.Entry<String, ?> entry : beanMap.entrySet()) {
    Object obj = entry.getValue();
    SalukiService salukiAnnotation = obj.getClass().getAnnotation(SalukiService.class);
    group = salukiAnnotation.group();
    version = salukiAnnotation.version();
    break;
  }
  if (StringUtils.isBlank(group) || StringUtils.isBlank(version)) {
    group = prop.getGroup();
    version = prop.getVersion();
  }
  return new ImmutablePair<String, String>(group, version);

}
项目:NGB-master    文件:AbstractHTTPCommandHandler.java   
/**
 * Method splits path for file registartion into file-index pair
 * @param path input CLI argument
 * @return pair, where left part is path to file and rights one optional path to index
 */
protected Pair<String, String> parseAndVerifyFilePath(String path) {
    Pair<String, String> fileWithIndex = splitFilePath(path);
    BiologicalDataItemFormat format = BiologicalDataItemFormat.getByFilePath(fileWithIndex.getLeft());
    if (format.isRequireIndex() && fileWithIndex.getRight() == null) {
        throw new IllegalArgumentException(getMessage(ERROR_INDEX_REQUIRED, fileWithIndex.getLeft()));
    }
    if (fileWithIndex.getRight() != null) {
        boolean indexSupported = format.verifyIndex(fileWithIndex.getRight());
        //if server doesn't support a given index, but index is also not required
        //we don't pass it to server
        if (!indexSupported) {
            return new ImmutablePair<>(fileWithIndex.getLeft(), null);
        }
    }
    return fileWithIndex;
}
项目:QDrill    文件:SessionOptionManager.java   
@Override
boolean setLocalOption(final OptionValue value) {
  final boolean set = super.setLocalOption(value);
  if (!set) {
    return false;
  }
  final String name = value.name;
  final OptionValidator validator = SystemOptionManager.getValidator(name); // if set, validator must exist.
  final boolean shortLived = validator.isShortLived();
  if (shortLived) {
    final int start = session.getQueryCount() + 1; // start from the next query
    final int ttl = validator.getTtl();
    final int end = start + ttl;
    shortLivedOptions.put(name, new ImmutablePair<>(start, end));
  }
  return true;
}
项目:NGB-master    文件:GeneRegisterer.java   
private void processLastFeature(GeneFeature feature, int featuresCount, GeneFile geneFile,
                                List<FeatureIndexEntry> allEntries, boolean doFeatureIndex) throws IOException {
    // Put the last one in metaMap
    if (feature != null) {
        endPosition = feature.getStart();
        if (currentKey != null) {
            metaMap.put(currentKey, new ImmutablePair<>(startPosition, endPosition));
            // Put the last one
            if (Utils.chromosomeMapContains(chromosomeMap, currentKey) && doFeatureIndex) {
                featureIndexManager.writeLuceneIndexForFile(geneFile, allEntries);
                allEntries.clear();
            }
        }
    }

    if (featuresCount > 0 && currentWig != null && currentChromosome != null) {
        currentWig.setValue((float) featuresCount);
        histogram.add(currentWig);
        fileManager.writeHistogram(geneFile, currentChromosome.getName(), histogram);
    }
}
项目:QDrill    文件:OperatorWrapper.java   
public String getContent() {
  TableBuilder builder = new TableBuilder(OPERATOR_COLUMNS);

  for (ImmutablePair<OperatorProfile, Integer> ip : ops) {
    int minor = ip.getRight();
    OperatorProfile op = ip.getLeft();

    String path = new OperatorPathBuilder().setMajor(major).setMinor(minor).setOperator(op).build();
    builder.appendCell(path, null);
    builder.appendNanos(op.getSetupNanos(), null);
    builder.appendNanos(op.getProcessNanos(), null);
    builder.appendNanos(op.getWaitNanos(), null);

    long maxBatches = Long.MIN_VALUE;
    long maxRecords = Long.MIN_VALUE;
    for (StreamProfile sp : op.getInputProfileList()) {
      maxBatches = Math.max(sp.getBatches(), maxBatches);
      maxRecords = Math.max(sp.getRecords(), maxRecords);
    }

    builder.appendFormattedInteger(maxBatches, null);
    builder.appendFormattedInteger(maxRecords, null);
    builder.appendBytes(op.getPeakLocalMemoryAllocated(), null);
  }
  return builder.build();
}
项目:commercetools-sync-java    文件:ProductSync.java   
@Nonnull
private CompletionStage<Optional<Product>> updateProduct(@Nonnull final Product oldProduct,
                                                         @Nonnull final ProductDraft newProduct,
                                                         @Nonnull final List<UpdateAction<Product>> updateActions) {
    return productService.updateProduct(oldProduct, updateActions)
                         .handle(ImmutablePair::new)
                         .thenCompose(updateResponse -> {
                             final Product updatedProduct = updateResponse.getKey();
                             final Throwable sphereException = updateResponse.getValue();
                             if (sphereException != null) {
                                 return executeSupplierIfConcurrentModificationException(sphereException,
                                     () -> fetchAndUpdate(oldProduct, newProduct),
                                     () -> {
                                         final String productKey = oldProduct.getKey();
                                         handleError(format(UPDATE_FAILED, productKey, sphereException),
                                             sphereException);
                                         return CompletableFuture.completedFuture(Optional.empty());
                                     });
                             } else {
                                 statistics.incrementUpdated();
                                 return CompletableFuture.completedFuture(Optional.of(updatedProduct));
                             }
                         });
}
项目:laozhongyi    文件:ProcessManager.java   
public synchronized Optional<Pair<List<ParamsAndCallable>, Integer>> removeCallables() {
    validate();
    for (int i = 1; i < 100; ++i) {
        final List<ParamsAndCallable> paramsAndCallables = mRunnableMap.get(i);
        final List<ParamsAndCallable> sortedParamsAndCallables = paramsAndCallables.stream()
                .sorted((a, b) -> Float.compare(HyperParamResultManager
                        .getResult(b.getParams(), b.getCallable().getTriedTimes()).get(),
                        HyperParamResultManager
                                .getResult(a.getParams(), a.getCallable().getTriedTimes())
                                .get()))
                .collect(Collectors.toList());

        if (!sortedParamsAndCallables.isEmpty()) {
            final List<ParamsAndCallable> removed = Lists.newArrayList();
            mRunnableMap.put(i, removed);

            return Optional.of(ImmutablePair.of(sortedParamsAndCallables, i));
        }
    }

    return Optional.empty();
}
项目:OperatieBRP    文件:GbaAutorisaties.java   
/**
 * Bepaal de GBA autorisatie.
 * @param partijCode partij
 * @param rol de rol waarvoor de autorisatie dient te bestaan (mag null zijn indien niet van toepassing)
 * @param soortDienst soort dienst
 * @return autorisatie
 * @throws MeerdereAutorisatiesGevondenException als er meeredere autorisaties gevonden worden
 */
Optional<Autorisatiebundel> bepaalAutorisatie(final String partijCode, final Rol rol, final SoortDienst soortDienst) {
    if (partijCode == null) {
        LOGGER.info("Geen autorisatie gevonden voor lege partijCode.");
        return Optional.empty();
    }

    final List<Autorisatiebundel> autorisatiebundels =
            leveringsAutorisatieCache.geefToegangleveringautorisatiesVoorGeautoriseerdePartij(partijCode).stream()
                    .filter(this::isGba)
                    .filter(this::isGeldig)
                    .filter(toegang -> Objects.isNull(rol) || rol == toegang.getGeautoriseerde().getRol())
                    .map(autorisatie -> ImmutablePair.of(autorisatie, bepaalDienst(autorisatie.getLeveringsautorisatie(), soortDienst)))
                    .filter(pair -> pair.getRight().isPresent())
                    .map(pair -> new Autorisatiebundel(pair.getLeft(), pair.getRight().orElseThrow(IllegalStateException::new)))
                    .collect(Collectors.toList());

    if (autorisatiebundels.size() > 1) {
        throw new MeerdereAutorisatiesGevondenException();
    } else {
        return autorisatiebundels.stream().findFirst();
    }
}
项目:bullet-core    文件:BufferingSubscriberTest.java   
@Test
public void testFailingUnknownMessage() throws PubSubException {
    List<PubSubMessage> messages = make(2);
    ExampleBufferingSubscriber subscriber = new ExampleBufferingSubscriber(1, messages);

    Assert.assertNotNull(subscriber.receive());

    Assert.assertNull(subscriber.receive());

    subscriber.commit(String.valueOf(0));
    // This doesn't exist
    subscriber.fail(String.valueOf(42));
    Assert.assertFalse(subscriber.unCommittedMessages.containsKey(ImmutablePair.of(String.valueOf(42), -1)));

    PubSubMessage actual = subscriber.receive();
    Assert.assertNotNull(actual);
    Assert.assertEquals(actual.getId(), String.valueOf(1));
    Assert.assertEquals(actual.getSequence(), -1);
    Assert.assertNotNull(actual.getContent());
}
项目:elastic-db-tools-for-java    文件:MultiShardStatement.java   
/**
 * Creates a list of commands to be executed against the shards associated with the connection.
 *
 * @return Pairs of shard locations and associated commands.
 */
private List<Pair<ShardLocation, Statement>> getShardCommands() {
    return this.connection.getShardConnections().stream().map(sc -> {
        try {
            Connection conn = sc.getRight();
            if (conn.isClosed()) {
                // TODO: This hack needs to be perfected. Reopening of connection is not straight forward.
                conn = getConnectionForLocation(sc.getLeft());
            }
            Statement statement = conn.prepareStatement(this.commandText, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            statement.setQueryTimeout(this.getCommandTimeoutPerShard());
            return new ImmutablePair<>(sc.getLeft(), statement);
        }
        catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }).collect(Collectors.toList());
}
项目:NGB-master    文件:HistogramUtils.java   
/**
 * Creates histogram block intervals for a histogram of specified size
 *
 * @param trackStart start index of histogram track
 * @param trackEnd end index of histogram track
 * @return list of intervals, representing histogram blocks
 */
public static List<Pair<Integer, Integer>> createIntervals(final int trackStart, final int trackEnd) {
    // limit to 1000!!!
    final int histogramSize = Math.min((int) Math.ceil(trackEnd * HISTOGAM_BLOCK_SIZE_PART), HISTOGRAM_SIZE_LIMIT);
    final int intervalLength = (trackEnd - trackStart) / histogramSize;
    final List<Pair<Integer, Integer>> intervals = new ArrayList<>(histogramSize);
    for (int i = 0; i < histogramSize; i++) {
        final int startIndex = trackStart + intervalLength * i;
        int endIndex = trackStart + intervalLength * (i + 1);
        if (endIndex > trackEnd) {
            endIndex = trackEnd;
        }

        intervals.add(new ImmutablePair<>(startIndex, endIndex));
    }
    return intervals;
}
项目:athena    文件:OltPipeline.java   
private List<Pair<Instruction, Instruction>> findVlanOps(List<Instruction> instructions,
                                                         L2ModificationInstruction.L2SubType type) {

    List<Instruction> vlanPushs = findL2Instructions(
            type,
            instructions);
    List<Instruction> vlanSets = findL2Instructions(
            L2ModificationInstruction.L2SubType.VLAN_ID,
            instructions);

    if (vlanPushs.size() != vlanSets.size()) {
        return null;
    }

    List<Pair<Instruction, Instruction>> pairs = Lists.newArrayList();

    for (int i = 0; i < vlanPushs.size(); i++) {
        pairs.add(new ImmutablePair<>(vlanPushs.get(i), vlanSets.get(i)));
    }
    return pairs;
}
项目:taboola-cronyx    文件:ConfigUtil.java   
public static <T> List<Pair<Class, T>> cronyxQuartzConverterPairs(Class<T> tClass) {

        List<Pair<Class, T>> results = new ArrayList<>();

        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        provider.addIncludeFilter(new AssignableTypeFilter(tClass));

        Set<BeanDefinition> components = provider.findCandidateComponents(PACKAGE);
        for (BeanDefinition component : components) {
            try {
                Class cls = Class.forName(component.getBeanClassName());
                Class<?> typeArgument = GenericTypeResolver.resolveTypeArgument(cls, tClass);
                results.add(new ImmutablePair<>(typeArgument, (T) cls.newInstance()));

            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                throw new CronyxException("Could not instantiate cronyxToQuartzConverters", e);
            }
        }
        return results;
    }
项目:NGB-master    文件:ProteinSequenceManager.java   
private List<List<ImmutablePair<Gene, List<Sequence>>>> recursiveCombine(
        List<List<ImmutablePair<Gene, List<Sequence>>>> acc,
        List<List<ImmutablePair<Gene, List<Sequence>>>> source) {
    if (source.isEmpty()) {
        return acc;
    }
    List<ImmutablePair<Gene, List<Sequence>>> nextLevel = source.remove(0);
    List<List<ImmutablePair<Gene, List<Sequence>>>> newAcc = new ArrayList<>();
    for (ImmutablePair<Gene, List<Sequence>> p : nextLevel) {
        for (List<ImmutablePair<Gene, List<Sequence>>> list : acc) {
            List<ImmutablePair<Gene, List<Sequence>>> newList = new ArrayList<>();
            newList.addAll(list);
            newList.add(p);
            newAcc.add(newList);
        }
    }
    return recursiveCombine(newAcc, source);
}
项目:datax    文件:RangeSplitUtil.java   
/**
 * 获取字符串中的最小字符和最大字符(依据 ascii 进行判断).要求字符串必须非空,并且为 ascii 字符串.
 * 返回的Pair,left=最小字符,right=最大字符.
 */
public static Pair<Character, Character> getMinAndMaxCharacter(String aString) {
    if (!isPureAscii(aString)) {
        throw new IllegalArgumentException(String.format("根据字符串进行切分时仅支持 ASCII 字符串,而字符串:[%s]非 ASCII 字符串.", aString));
    }

    char min = aString.charAt(0);
    char max = min;

    char temp;
    for (int i = 1, len = aString.length(); i < len; i++) {
        temp = aString.charAt(i);
        min = min < temp ? min : temp;
        max = max > temp ? max : temp;
    }

    return new ImmutablePair<Character, Character>(min, max);
}
项目:smarti    文件:MltConfig.java   
public Map.Entry<String,Collection<String>> getSimilarityFields(String lang, boolean fallback) {
    lang = StringUtils.lowerCase(lang, Locale.ROOT);
    Collection<String> langFields = langSimilarityFields.get(lang);
    if(fallback){
        int sepIdx = StringUtils.indexOfAny(lang, '-','_');
        if(sepIdx > 0){
            lang = lang.substring(0, sepIdx);
            langFields = langSimilarityFields.get(lang);
        }
        if(langFields == null && lang != null){
            lang = null;
            langFields = langSimilarityFields.get(lang);
        }
    } //else no fallback
    return langFields == null ? null : new ImmutablePair<>(lang, langFields);
}
项目:NGB-master    文件:ProteinSequenceManager.java   
private List<List<ImmutablePair<Gene, List<Sequence>>>> combineData(
        final Map<Gene, List<List<Sequence>>> data,
        final Comparator<Gene> comparator) {
    List<List<ImmutablePair<Gene, List<Sequence>>>> source =
            data.entrySet().stream().sorted((e1, e2) -> comparator.compare(e1.getKey(), e2.getKey()))
                    .map(e -> e.getValue().stream().map(s -> new ImmutablePair<>(e.getKey(), s))
                            .collect(Collectors.toList())).collect(Collectors.toList());
    if (CollectionUtils.isEmpty(source)) {
        return Collections.emptyList();
    }
    List<List<ImmutablePair<Gene, List<Sequence>>>> start = new ArrayList<>();
    for (ImmutablePair<Gene, List<Sequence>> p : source.remove(0)) {
        List<ImmutablePair<Gene, List<Sequence>>> ll = new ArrayList<>();
        ll.add(p);
        start.add(ll);
    }
    return recursiveCombine(start, source);
}
项目:smarti    文件:ConversationRepositoryImpl.java   
@Override
public List<Pair<String, Long>> findTags(long limit, long offset) {
    final Aggregation agg = newAggregation(
            project("meta.tags"),
            unwind("tags"),
            group("tags").count().as("count"),
            project("count").and("tags").previousOperation(),
            sort(Direction.DESC, "count"),
            skip(offset),
            limit(limit));

    final AggregationResults<DBObject> results = mongoTemplate.aggregate(agg, Conversation.class, DBObject.class);
    return results.getMappedResults()
            .stream()
            .map(i -> new ImmutablePair<>((String) i.get("tags"), (long) i.get("count")))
            .collect(Collectors.toList());
}
项目:smarti    文件:QueryBuilderService.java   
/**
 * Getter for the QueryBuilder for the parsed creator string
 * @param creator the creator string formated as '<code>queryBuilder/{queryBuilder#getName()}/{config#getName()}</code>'
 * where '<code>{queryBuilder#getName()}</code>' is the same as '<code>{config#getType()}</code>'
 * @return the {@link QueryBuilder} or <code>null</code> if not present
 */
public <C extends ComponentConfiguration> Entry<QueryBuilder<C>,C> getQueryBuilder(String creator, Configuration conf) {
    String[] creatorParts = StringUtils.split(creator, ':');
    if(creatorParts.length >= 2){
        QueryBuilder<C> queryBuilder = (QueryBuilder<C>)builders.get(creatorParts[1]);
        if(queryBuilder == null){
            return null;
        }
        if(creatorParts.length >= 3){
            Optional<C> config = conf.getConfiguration(queryBuilder,creatorParts[2]);
            if(config.isPresent()){
                return new ImmutablePair<>(queryBuilder, config.get());
            } else { //the referenced config was not found
                return null;
            }
        } else { //no configuration in the creator string ... so a null configuration is OK
            return new ImmutablePair<>(queryBuilder, null);
        }
    } else {
        return null;
    }
}
项目:dremio-oss    文件:SessionOptionManager.java   
@Override
boolean setLocalOption(final OptionValue value) {
  final boolean set = super.setLocalOption(value);
  if (!set) {
    return false;
  }
  final String name = value.name;
  final OptionValidator validator = getValidator(name); // if set, validator must exist.
  final boolean shortLived = validator.isShortLived();
  if (shortLived) {
    final int start = session.getQueryCount() + 1; // start from the next query
    final int ttl = validator.getTtl();
    final int end = start + ttl;
    shortLivedOptions.put(name, new ImmutablePair<>(start, end));
  }
  return true;
}
项目:dremio-oss    文件:LocalDictionariesReader.java   
/**
 * Return dictionary per row group for all binary columns in given parquet file.
 * @param fs filesystem object.
 * @param filePath parquet file to scan
 * @return pair of dictionaries found for binary fields and list of binary fields which are not dictionary encoded.
 * @throws IOException
 */
public static Pair<Map<ColumnDescriptor, Dictionary>, Set<ColumnDescriptor>> readDictionaries(FileSystem fs, Path filePath, CodecFactory codecFactory) throws IOException {
  final ParquetMetadata parquetMetadata = ParquetFileReader.readFooter(fs.getConf(), filePath, ParquetMetadataConverter.NO_FILTER);
  if (parquetMetadata.getBlocks().size() > 1) {
    throw new IOException(
      format("Global dictionaries can only be built on a parquet file with a single row group, found %d row groups for file %s",
        parquetMetadata.getBlocks().size(), filePath));
  }
  final BlockMetaData rowGroupMetadata = parquetMetadata.getBlocks().get(0);
  final Map<ColumnPath, ColumnDescriptor> columnDescriptorMap = Maps.newHashMap();

  for (ColumnDescriptor columnDescriptor : parquetMetadata.getFileMetaData().getSchema().getColumns()) {
    columnDescriptorMap.put(ColumnPath.get(columnDescriptor.getPath()), columnDescriptor);
  }

  final Set<ColumnDescriptor> columnsToSkip = Sets.newHashSet(); // columns which are found in parquet file but are not dictionary encoded
  final Map<ColumnDescriptor, Dictionary> dictionaries = Maps.newHashMap();
  try(final FSDataInputStream in = fs.open(filePath)) {
    for (ColumnChunkMetaData columnChunkMetaData : rowGroupMetadata.getColumns()) {
      if (isBinaryType(columnChunkMetaData.getType())) {
        final ColumnDescriptor column = columnDescriptorMap.get(columnChunkMetaData.getPath());
        // if first page is dictionary encoded then load dictionary, otherwise skip this column.
        final PageHeaderWithOffset pageHeader = columnChunkMetaData.getPageHeaders().get(0);
        if (PageType.DICTIONARY_PAGE == pageHeader.getPageHeader().getType()) {
          dictionaries.put(column, readDictionary(in, column, pageHeader, codecFactory.getDecompressor(columnChunkMetaData.getCodec())));
        } else {
          columnsToSkip.add(column);
        }
      }
    }
  }
  return new ImmutablePair<>(dictionaries, columnsToSkip);
}
项目:echo    文件:NifiDeployer.java   
private Pair<Device, NifiKafkaPort> getDeviceAndKafkaPort(int portId, Map<Device, List<NifiKafkaPort>> lKafkaPortMap) {
    for (Map.Entry<Device, List<NifiKafkaPort>> entry : lKafkaPortMap.entrySet()) {
        for (NifiKafkaPort nifiKafkaPort : entry.getValue()) {
            if (nifiKafkaPort.getId() == portId) {
                return new ImmutablePair<>(entry.getKey(), nifiKafkaPort);
            }
        }
    }
    return null;
}
项目:stvs    文件:TimingDiagramController.java   
/**
 * Generates an enum timing diagram.
 *
 * @param concreteSpec the concrete specification which should be used to extract the needed
 *        information
 * @param specIoVar the variable for which a diagram should be generated
 * @param typeEnum type of the enum this diagram is generated for
 * @param globalXAxis  global x axis used for all diagrams
 * @param selection selection that should be updated when hovering with mouse
 * @param activated only update selection if true
 * @return A {@link Pair} which holds a {@link TimingDiagramController} and a {@link CategoryAxis}
 */
public static Pair<TimingDiagramController, Axis> createEnumTimingDiagram(
    ConcreteSpecification concreteSpec, ValidIoVariable specIoVar, TypeEnum typeEnum,
    NumberAxis globalXAxis, Selection selection, BooleanProperty activated) {
  ObservableList<String> categories = FXCollections.observableArrayList();
  typeEnum.getValues().stream().map(ValueEnum::getEnumValue).forEach(categories::add);
  CategoryAxis categoryAxis = new CategoryAxis(categories);
  categoryAxis.setSide(Side.LEFT);
  categoryAxis.setPrefWidth(30);
  categoryAxis.setAutoRanging(true);
  TimingDiagramController timingDiagramController = new TimingDiagramController(globalXAxis,
      categoryAxis, concreteSpec, specIoVar, selection, activated);
  return new ImmutablePair<>(timingDiagramController, categoryAxis);
}
项目:echo    文件:NifiDeployer.java   
private Pair<Device, NifiRPG> getDeviceAndRpg(int rpgId, Map<Device, List<NifiRPG>> lrpgMap) {
    for (Map.Entry<Device, List<NifiRPG>> entry : lrpgMap.entrySet()) {
        for (NifiRPG rpg : entry.getValue()) {
            if (rpg.getId() == rpgId) {
                return new ImmutablePair<>(entry.getKey(), rpg);
            }
        }
    }
    return null;
}
项目:nequithon    文件:LoanProvider.java   
public ArrayList<Pair<String, String>> getCurrentMilestones() {
    ArrayList<Pair<String, String>> milestones = new ArrayList<>();
    milestones.add(new ImmutablePair<>("", "Conseguiste los "+ Utils.getPrettyAmount(currentLoan.getPayments().get(0).getShouldPay()) +" <span class=\"badge badge-success badge-pill\"><i class=\"fa fa-check\" aria-hidden=\"true\"></i></span>"));
    milestones.add(new ImmutablePair<>("", "Conseguiste los "+ Utils.getPrettyAmount(currentLoan.getPayments().get(1).getShouldPay()) +" <span class=\"badge badge-success badge-pill\"><i class=\"fa fa-check\" aria-hidden=\"true\"></i></span>"));
    milestones.add(new ImmutablePair<>("list-group-item-danger", "¡Recarga a "+ Utils.getPrettyAmount(currentLoan.getPayments().get(2).getMissing()) +"! <span class=\"badge badge-danger badge-pill\"><i class=\"fa fa-warning\" aria-hidden=\"true\"></i></span>"));
    milestones.add(new ImmutablePair<>("disabled", "<i class=\"fa fa-lock text-size-l\" aria-hidden=\"true\"></i> Paga la meta anterior primero"));
    milestones.add(new ImmutablePair<>("disabled text-size-l", "<i class=\"fa fa-lock\" aria-hidden=\"true\"></i>"));

    return milestones;
}
项目:NGB-master    文件:AbstractHTTPCommandHandler.java   
private Pair<String, String> splitFilePath(String path) {
    String[] paths = path.split(INDEX_DELIMITER);
    if (paths.length > 2) {
        throw new IllegalArgumentException(getMessage(ILLEGAL_PATH_FORMAT, path));
    }
    if (paths.length == 1) {
        return new ImmutablePair<>(paths[0], null);
    } else {
        return new ImmutablePair<>(paths[0], paths[1]);
    }
}