org.apache.commons.lang3.tuple.Pair#of ( )源码实例Demo

下面列出了org.apache.commons.lang3.tuple.Pair#of ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: dremio-oss   文件: Checker.java
public static Checker getChecker(int min, int max) {
  final Pair<Integer, Integer> range = Pair.of(min, max);
  if(checkerMap.containsKey(range)) {
    return checkerMap.get(range);
  }

  final Checker newChecker;
  if(min == max) {
    newChecker = new Checker(min);
  } else {
    newChecker = new Checker(min, max);
  }

  checkerMap.put(range, newChecker);
  return newChecker;
}
 
源代码2 项目: datacollector   文件: TestRemoteDownloadSource.java
private Pair<String, List<Record>> runSourceAndReturnOffsetAndRecords(
    String lastOffset,
    int batchSize
) throws Exception {
  RemoteDownloadSource origin = new TestRemoteDownloadSourceBuilder(scheme, port)
      .withDataFormat(DataFormat.TEXT)
      .withFilePattern("*.zip")
      .withDataFormatCompression(Compression.ARCHIVE)
      .withFilePatternInArchive("testReadArchive/*.txt")
      .build();
  SourceRunner runner = new SourceRunner.Builder(RemoteDownloadDSource.class, origin)
      .addOutputLane("lane")
      .build();
  runner.runInit();
  try {
    StageRunner.Output op = runner.runProduce(lastOffset, batchSize);
    List<Record> records = op.getRecords().get("lane");
    return Pair.of(op.getNewOffset(), records);
  } finally {
    destroyAndValidate(runner);
  }
}
 
源代码3 项目: Bats   文件: PruneScanRule.java
/** Compose the array of partition values for the directories that are referenced by filter:
 *  e.g suppose the dir hierarchy is year/quarter/month and the query is:
 *     SELECT * FROM T WHERE dir0=2015 AND dir1 = 'Q1',
 * then for 2015/Q1/Feb, this will have ['2015', 'Q1', null]
 * If the query filter condition is WHERE dir1 = 'Q2'  (i.e no dir0 condition) then the array will
 * have [null, 'Q2', null]
 */
private Pair<String[], Integer> composePartition(BitSet referencedDirsBitSet,
    Map<Integer, Integer> partitionMap,
    ValueVector[] vectors,
    int recordCount) {
  String[] partition = new String[vectors.length];
  int maxIndex = -1;
  for (int referencedDirsIndex : BitSets.toIter(referencedDirsBitSet)) {
    int partitionColumnIndex = partitionMap.get(referencedDirsIndex);
    ValueVector vv = vectors[partitionColumnIndex];
    if (vv.getAccessor().getValueCount() > 0 &&
        vv.getAccessor().getObject(recordCount) != null) {
      String value = vv.getAccessor().getObject(recordCount).toString();
      partition[partitionColumnIndex] = value;
      maxIndex = Math.max(maxIndex, partitionColumnIndex);
    }
  }
  return Pair.of(partition, maxIndex);
}
 
源代码4 项目: jopenfst   文件: GallicSemiring.java
/**
 * Factorize a gallic weight into the (head x weight, rest x One); the contract of factorize is that:
 * val (factor1, factor2) = factorize(weight) implies weight = times(factor1, factor2)
 * (see openfst's GallicFactor)
 * @param weight gallic weight to factorize
 * @return
 */
public Pair<GallicWeight, GallicWeight> factorize(GallicWeight weight) {
  Preconditions.checkArgument(isNotZero(weight), "cannot factorize a zero weight");
  IntArrayList labels = weight.getLabels();
  if (labels.isEmpty()) {
    return Pair.of(GallicWeight.createEmptyLabels(weight.getWeight()), one());
  }
  if (labels.size() == 1) {
    return Pair.of(GallicWeight.createSingleLabel(labels.get(0), weight.getWeight()), one());
  }
  IntArrayList prefix = new IntArrayList(1);
  IntArrayList suffix = new IntArrayList(labels.size() - 1);
  prefix.add(labels.get(0));
  for (int i = 1; i < labels.size(); i++) {
    suffix.add(labels.get(i));
  }
  return Pair.of(GallicWeight.create(prefix, weight.getWeight()), GallicWeight.create(suffix, weightSemiring.one()));
}
 
源代码5 项目: TranskribusCore   文件: GeomUtils.java
/**
	 * Returns the distance and the closest segment of a point (x,y) to a polygon given as a series of points
	 * @param isClosedShape True if this is a closes polygon or false if its a polyline
	 */
	public static Pair<Double, java.awt.geom.Line2D.Double> 
		getDistToPolygonAndClosestSegment(List<Point> pts, double x, double y, boolean isClosedShape) {
		double minDist = Integer.MAX_VALUE;
		java.awt.geom.Line2D.Double minLine = new java.awt.geom.Line2D.Double(0, 0, 0, 0);
		
		int N = isClosedShape ? pts.size() : pts.size()-1;
		
		for (int i=0; i<N; ++i) {
			java.awt.geom.Line2D.Double line = new java.awt.geom.Line2D.Double(pts.get(i), pts.get( (i+1) % pts.size() ));
			double d = line.ptSegDistSq(x, y);
//			logger.debug("d = "+d);
			if (d < minDist) {
				minDist = d;
				minLine = line;
			}
		}

		return Pair.of(minDist, minLine);
	}
 
源代码6 项目: codehelper.generator   文件: OnePojoInfoHelper.java
public static Pair<List<ChangeInfo>, List<ChangeInfo>> statisticChange(List<OnePojoInfo> onePojoInfos){
    List<ChangeInfo> newFiles = Lists.newArrayList();
    List<ChangeInfo> updatedFiles = Lists.newArrayList();
    for (OnePojoInfo onePojoInfo : onePojoInfos) {
        for (GeneratedFile file : onePojoInfo.getFiles()) {
            if(file.getOriginLines().isEmpty()){
                ChangeInfo newFile = new ChangeInfo();
                newFile.setFileName(file.getFile().getName());
                newFile.setAffectRow(file.getNewLines().size());
                newFile.setChangeType("new file");
                newFiles.add(newFile);
            }else{
                ChangeInfo updatedFile = new ChangeInfo();
                updatedFile.setFileName(file.getFile().getName());
                updatedFile.setAffectRow(countChangeRows(file.getNewLines(), file.getOriginLines()));
                updatedFile.setChangeType("updated");
                updatedFiles.add(updatedFile);
            }
        }
    }
    return Pair.of(newFiles, updatedFiles);
    
}
 
/**
 * Converts cross connect flow rule to module and connection.
 *
 * Connection number is incremental within the class and associated to the rule hash.
 *
 * @param xc the cross connect flow rule
 * @return pair of module (1 for MUX/ADD, 2 for DEMUX/DROP) and connection number
 */
private Pair<Short, Short> setModuleConnection(LumentumFlowRule xc, Integer id) {
    if (xc.isAddRule()) {
        xc.setConnectionModule((short) 1);
        xc.setConnectionId(id.shortValue());
        return Pair.of((short) 1, id.shortValue());
    } else {
        xc.setConnectionModule((short) 2);
        xc.setConnectionId(id.shortValue());
        return Pair.of((short) 2, id.shortValue());
    }
}
 
源代码8 项目: Kepler   文件: MoodlightDao.java
public static Pair<Integer, ArrayList<String>> getPresets(int itemId) {
    Pair<Integer, ArrayList<String>> presetData = null;

    Connection sqlConnection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;

    try {
        sqlConnection = Storage.getStorage().getConnection();
        preparedStatement = Storage.getStorage().prepare("SELECT * FROM items_moodlight_presets WHERE item_id = ? LIMIT 1", sqlConnection);
        preparedStatement.setInt(1, itemId);
        resultSet = preparedStatement.executeQuery();

        if (resultSet.next()) {
            ArrayList<String> presets = new ArrayList<>();
            presets.add(resultSet.getString("preset_1"));
            presets.add(resultSet.getString("preset_2"));
            presets.add(resultSet.getString("preset_3"));

            presetData = Pair.of(resultSet.getInt("current_preset"), presets);
        }

    } catch (Exception e) {
        Storage.logError(e);
    } finally {
        Storage.closeSilently(preparedStatement);
        Storage.closeSilently(sqlConnection);
    }

    return presetData;
}
 
源代码9 项目: azure-keyvault-java   文件: KeyVaultCredentials.java
/**
 * Builds request with authenticated header. Protects request body if supported.
 *
 * @param originalRequest
 *            unprotected request without auth token.
 * @param challengeMap
 *            the challenge map.
 * @return Pair of protected request and HttpMessageSecurity used for
 *         encryption.
 */
private Pair<Request, HttpMessageSecurity> buildAuthenticatedRequest(Request originalRequest,
        Map<String, String> challengeMap) throws IOException {

    Boolean supportsPop = supportsMessageProtection(originalRequest.url().toString(), challengeMap);

    // if the service supports pop and a clientEncryptionKey has not been generated yet, generate
    // the key that will be used for encryption on this and all subsequent protected requests
    if (supportsPop && this.clientEncryptionKey == null)
    {
        try {
            final KeyPairGenerator generator = KeyPairGenerator.getInstance(CLIENT_ENCRYPTION_KEY_TYPE);

            generator.initialize(CLIENT_ENCRYPTION_KEY_SIZE);
            
            this.clientEncryptionKey = JsonWebKey.fromRSA(generator.generateKeyPair()).withKid(UUID.randomUUID().toString());   
            
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    AuthenticationResult authResult = getAuthenticationCredentials(supportsPop, challengeMap);

    if (authResult == null) {
        return null;
    }

    HttpMessageSecurity httpMessageSecurity = new HttpMessageSecurity(authResult.getAuthToken(),
            supportsPop ? authResult.getPopKey() : "",
            supportsPop ? challengeMap.get("x-ms-message-encryption-key") : "",
            supportsPop ? challengeMap.get("x-ms-message-signing-key") : "",
            this.clientEncryptionKey);

    Request request = httpMessageSecurity.protectRequest(originalRequest);
    return Pair.of(request, httpMessageSecurity);
}
 
private Pair<String, GobblinTrackingEvent> nextKVEvent(Iterator<Pair<String, byte[]>> it, boolean isSchemaIdEnabled) throws IOException {
  Assert.assertTrue(it.hasNext());
  Pair<String, byte[]> event = it.next();
  return isSchemaIdEnabled ? Pair.of(event.getKey(), EventUtils
      .deserializeEventFromAvroSerialization(new GobblinTrackingEvent(), event.getValue(), schemaId)) : Pair.of(event.getKey(),
      EventUtils.deserializeEventFromAvroSerialization(new GobblinTrackingEvent(), event.getValue()));
}
 
源代码11 项目: james-project   文件: MappingArgument.java
private static Pair<String, String> parseKeyValue(String keyValue) {
    List<String> pair = Splitter.on(';')
        .trimResults()
        .splitToList(keyValue);

    if (pair.size() != 2) {
        throw new IllegalArgumentException(CONFIGURATION_ERROR_MESSAGE);
    }

    return Pair.of(pair.get(0), pair.get(1));
}
 
源代码12 项目: dremio-flight-connector   文件: SslHelper.java
static Pair<InputStream, InputStream> ssl(DremioConfig config, String hostName) throws Exception {
  final SSLConfigurator configurator = new SSLConfigurator(config, DremioConfig.WEB_SSL_PREFIX, "web");
  final Optional<SSLConfig> sslConfigOption = configurator.getSSLConfig(true, hostName);
  Preconditions.checkState(sslConfigOption.isPresent()); // caller's responsibility
  final SSLConfig sslConfig = sslConfigOption.get();

  final KeyStore keyStore = KeyStore.getInstance(sslConfig.getKeyStoreType());
  try (InputStream stream = Files.newInputStream(Paths.get(sslConfig.getKeyStorePath()))) {
    keyStore.load(stream, sslConfig.getKeyStorePassword().toCharArray());
  }

  boolean isAliasWithPrivateKey = false;
  Enumeration<String> es = keyStore.aliases();
  String alias = "";
  while (es.hasMoreElements()) {
    alias = (String) es.nextElement();
    // if alias refers to a private key break at that point
    // as we want to use that certificate
    if (isAliasWithPrivateKey = keyStore.isKeyEntry(alias)) {
      break;
    }
  }

  if (isAliasWithPrivateKey) {

    KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,
      new KeyStore.PasswordProtection(sslConfig.getKeyPassword().toCharArray()));

    PrivateKey myPrivateKey = pkEntry.getPrivateKey();


    // Load certificate chain
    Certificate[] chain = keyStore.getCertificateChain(alias);
    return Pair.of(keyToStream(myPrivateKey), certsToStream(chain));
  }

  return null;
}
 
源代码13 项目: distributedlog   文件: TestZKSessionLock.java
@Test(timeout = 60000)
public void testParseClientID() throws Exception {
    ZooKeeper zk = zkc.get();

    String lockPath = "/test-parse-clientid";
    String clientId = "test-parse-clientid-" + System.currentTimeMillis();
    Pair<String, Long> lockId = Pair.of(clientId, zk.getSessionId());

    createLockPath(zk, lockPath);

    // Correct data
    String node1 = getLockIdFromPath(createLockNodeV1(zk, lockPath, clientId));
    String node2 = getLockIdFromPath(createLockNodeV2(zk, lockPath, clientId));
    String node3 = getLockIdFromPath(createLockNodeV3(zk, lockPath, clientId));

    assertEquals(lockId, Utils.ioResult(asyncParseClientID(zk, lockPath, node1)));
    assertEquals(lockId, Utils.ioResult(asyncParseClientID(zk, lockPath, node2)));
    assertEquals(lockId, Utils.ioResult(asyncParseClientID(zk, lockPath, node3)));

    // Bad Lock Node Name
    String node4 = getLockIdFromPath(createLockNodeWithBadNodeName(zk, lockPath, clientId, "member"));
    String node5 = getLockIdFromPath(createLockNodeWithBadNodeName(zk, lockPath, clientId, "member_badnode"));
    String node6 = getLockIdFromPath(
            createLockNodeWithBadNodeName(zk, lockPath, clientId, "member_badnode_badnode"));
    String node7 = getLockIdFromPath(
            createLockNodeWithBadNodeName(zk, lockPath, clientId, "member_badnode_badnode_badnode"));
    String node8 = getLockIdFromPath(
            createLockNodeWithBadNodeName(zk, lockPath, clientId, "member_badnode_badnode_badnode_badnode"));

    assertEquals(lockId, Utils.ioResult(asyncParseClientID(zk, lockPath, node4)));
    assertEquals(lockId, Utils.ioResult(asyncParseClientID(zk, lockPath, node5)));
    assertEquals(lockId, Utils.ioResult(asyncParseClientID(zk, lockPath, node6)));
    assertEquals(lockId, Utils.ioResult(asyncParseClientID(zk, lockPath, node7)));
    assertEquals(lockId, Utils.ioResult(asyncParseClientID(zk, lockPath, node8)));

    // Malformed Node Name
    String node9 = getLockIdFromPath(
            createLockNodeWithBadNodeName(zk, lockPath, clientId, "member_malformed_s12345678_999999"));
    assertEquals(Pair.of("malformed", 12345678L), Utils.ioResult(asyncParseClientID(zk, lockPath, node9)));
}
 
源代码14 项目: fabric-carpet   文件: SpawnReporter.java
public static List<BaseText> tracking_report(World worldIn)
{

    List<BaseText> report = new ArrayList<>();
    if (track_spawns == 0L)
    {
        report.add(Messenger.c(
                "w Spawn tracking disabled, type '",
                "wi /spawn tracking start","/spawn tracking start",
                "w ' to enable"));
        return report;
    }
    long duration = (long) worldIn.getServer().getTicks() - track_spawns;
    report.add(Messenger.c("bw --------------------"));
    String simulated = mock_spawns?"[SIMULATED] ":"";
    String location = (lower_spawning_limit != null)?String.format("[in (%d, %d, %d)x(%d, %d, %d)]",
            lower_spawning_limit.getX(),lower_spawning_limit.getY(),lower_spawning_limit.getZ(),
            upper_spawning_limit.getX(),upper_spawning_limit.getY(),upper_spawning_limit.getZ() ):"";
    report.add(Messenger.s(String.format("%sSpawn statistics %s: for %.1f min", simulated, location, (duration/72000.0)*60)));
    for (EntityCategory enumcreaturetype : EntityCategory.values())
    {
        //String type_code = String.format("%s", enumcreaturetype);
        boolean there_are_mobs_to_list = false;
        for (DimensionType dim: DimensionType.getAll()) //String world_code: new String[] {"", " (N)", " (E)"})
        {
            Pair<DimensionType, EntityCategory> code = Pair.of(dim, enumcreaturetype);
            if (spawn_ticks_spawns.get(code) > 0L)
            {
                there_are_mobs_to_list = true;
                double hours = overall_spawn_ticks.get(code)/72000.0;
                report.add(Messenger.s(String.format(" > %s (%.1f min), %.1f m/t, {%.1f%%F / %.1f%%- / %.1f%%+}; %.2f s/att",
                    code.getRight()+((code.getLeft()==DimensionType.OVERWORLD)?"":( (code.getLeft()==DimensionType.THE_NETHER)?"(N)":"(E)" )),
                    60*hours,
                    (1.0D*spawn_cap_count.get(code))/ spawn_attempts.get(code),
                    (100.0D*spawn_ticks_full.get(code))/ spawn_attempts.get(code),
                    (100.0D*spawn_ticks_fail.get(code))/ spawn_attempts.get(code),
                    (100.0D*spawn_ticks_succ.get(code))/ spawn_attempts.get(code),
                    (1.0D*spawn_ticks_spawns.get(code))/(spawn_ticks_fail.get(code)+spawn_ticks_succ.get(code))
                )));
                for (EntityType type: spawn_stats.get(code).keySet())
                {
                    report.add(Messenger.s(String.format("   - %s: %d spawns, %d per hour",
                            type.getName().getString(),
                            spawn_stats.get(code).getLong(type),
                            (72000 * spawn_stats.get(code).getLong(type)/duration ))));
                }
            }
        }
    }
    return report;
}
 
源代码15 项目: GregTech   文件: SteamBoiler.java
@SideOnly(Side.CLIENT)
@Override
public Pair<TextureAtlasSprite, Integer> getParticleTexture() {
    return Pair.of(getBaseRenderer().getParticleSprite(), getPaintingColor());
}
 
protected Pair<String, LocalDate> getLastReferences(BankOrderLine bankOrderLine) {

    String lastReferenceId = "";
    LocalDate lastReferenceDate = null;

    for (BankOrderLineOrigin bankOrderLineOrigin : bankOrderLine.getBankOrderLineOriginList()) {
      LocalDate originDate = null;
      String originReferenceId = null;

      switch (bankOrderLineOrigin.getRelatedToSelect()) {
        case BankOrderLineOriginRepository.RELATED_TO_INVOICE:
          Invoice invoice = invoiceRepository.find(bankOrderLineOrigin.getRelatedToSelectId());
          if (!Strings.isNullOrEmpty(invoice.getSupplierInvoiceNb())) {
            originReferenceId = invoice.getSupplierInvoiceNb();
          } else {
            originReferenceId = invoice.getInvoiceId();
          }
          if (!Strings.isNullOrEmpty(invoice.getSupplierInvoiceNb())) {
            originDate = invoice.getOriginDate();
          } else {
            originDate = invoice.getInvoiceDate();
          }
          break;

        case BankOrderLineOriginRepository.RELATED_TO_PAYMENT_SCHEDULE_LINE:
          PaymentScheduleLine paymentScheduleLine =
              paymentScheduleLineRepository.find(bankOrderLineOrigin.getRelatedToSelectId());
          originReferenceId = paymentScheduleLine.getName();
          originDate = paymentScheduleLine.getScheduleDate();
          break;

        default:
          break;
      }

      if (originDate != null
          && (lastReferenceDate == null || lastReferenceDate.isBefore(originDate))) {
        lastReferenceDate = originDate;
        lastReferenceId = originReferenceId;
      }
    }

    return Pair.of(lastReferenceId, lastReferenceDate);
  }
 
源代码17 项目: quaerite   文件: CustomHandlerFactory.java
@Override
public Pair<CustomHandler, CustomHandler> crossover(CustomHandler parentA, CustomHandler parentB) {
    return Pair.of(parentA.deepCopy(), parentB.deepCopy());
}
 
源代码18 项目: astor   文件: EqualsBuilder.java
/**
 * <p>
 * Returns <code>true</code> if the registry contains the given object pair.
 * Used by the reflection methods to avoid infinite loops.
 * Objects might be swapped therefore a check is needed if the object pair
 * is registered in given or swapped order.
 * </p>
 *
 * @param lhs <code>this</code> object to lookup in registry
 * @param rhs the other object to lookup on registry
 * @return boolean <code>true</code> if the registry contains the given object.
 * @since 3.0
 */
static boolean isRegistered(Object lhs, Object rhs) {
    Set<Pair<IDKey, IDKey>> registry = getRegistry();
    Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
    Pair<IDKey, IDKey> swappedPair = Pair.of(pair.getLeft(), pair.getRight());

    return registry != null
            && (registry.contains(pair) || registry.contains(swappedPair));
}
 
源代码19 项目: cryptotrader   文件: BitpointContext.java
@VisibleForTesting
Future<String> requestAsync(String path, String body) {

    String apiKey = getStringProperty("api.id", null);
    String secret = getStringProperty("api.secret", null);

    if (StringUtils.isEmpty(apiKey) || StringUtils.isEmpty(secret)) {
        return null;
    }

    CompletableFuture<String> future = new CompletableFuture<>();

    try {

        lock.lock();

        Pair<Instant, String> accessToken = token.get();

        Long millis = getLongProperty("api.expire", TimeUnit.MINUTES.toMillis(59));

        Instant now = getNow();

        if (accessToken == null || accessToken.getLeft().isBefore(now.minusMillis(millis))) {

            Map<String, String> parameters = new LinkedHashMap<>();
            parameters.put("username", apiKey);
            parameters.put("password", secret);

            String json = request(URL_CLASSIC + "/login" + buildQueryParameter(parameters, "?"));

            accessToken = Pair.of(now, MapUtils.getString(gson.fromJson(json, TYPE_TOKEN), ACCESS_TOKEN));

            token.set(accessToken);

        }

        // Requests must be serial (Error Code : E_BL_0023)

        Map<String, String> headers = singletonMap("Content-Type", "application/json");

        String query = buildQueryParameter(singletonMap(ACCESS_TOKEN, accessToken.getRight()), "?");

        future.complete(request(POST, URL_CLASSIC + path + query, headers, body));

    } catch (Exception e) {

        token.set(null); // TODO: Clear token only on authentication failure.

        future.completeExceptionally(e);

    } finally {

        lock.unlock();

    }

    return future;

}
 
源代码20 项目: logsniffer   文件: FieldJsonMapper.java
/**
 * Resolves the type name and serialize as class from current field value,
 * the first used later for correct deserialization. The serialize as class
 * can be null, which indicates that serialization should follow without
 * type indication.
 * 
 * @param fieldValue
 *            field value
 * @return simple type, in worst case {@link FieldBaseTypes#OBJECT} is
 *         always returned as fallback
 */
public <T> Pair<String, Class<Object>> resolveSerializationType(final T fieldValue) {
	final FieldBaseTypes type = FieldBaseTypes.resolveType(fieldValue);
	return Pair.of(type.name(), type.getSerializationType());
}