Java Code Examples for org.apache.commons.lang3.tuple.Triple#getRight()

The following examples show how to use org.apache.commons.lang3.tuple.Triple#getRight() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConsulRegistryService.java    From saluki with Apache License 2.0 6 votes vote down vote up
private void processApplication(Map<String, Application> appCache,
                                Map.Entry<String, Pair<Set<GrpcHost>, Set<GrpcHost>>> entry) {
    Triple<String, String, String> appNameServiceVersion = getAppNameServiceVersion(entry.getKey());
    Pair<Set<GrpcHost>, Set<GrpcHost>> providerConsumer = entry.getValue();
    String appName = appNameServiceVersion.getLeft();
    String serviceName = appNameServiceVersion.getMiddle();
    String version = appNameServiceVersion.getRight();
    Application application = new Application(appName);
    GrpcService service = new GrpcService(appName, version, serviceName);
    if (providerConsumer.getLeft() != null) {
        service.addProviderHosts(providerConsumer.getLeft());
    }
    if (providerConsumer.getRight() != null) {
        service.addConsumerHosts(providerConsumer.getRight());
    }
    application.addService(service);
    if (appCache.get(application.getAppName()) == null) {
        appCache.put(application.getAppName(), application);
    } else {
        appCache.get(application.getAppName()).addServices(application.getServices());
    }
}
 
Example 2
Source File: AesCbcHmacSha2.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
AesCbcHmacSha2Decryptor(String name, byte[] key, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException {

            // Split the key to get the AES key, the HMAC key and the HMAC
            // object
            Triple<byte[], byte[], Mac> parameters = GetAlgorithmParameters(name, key);

            // Save the MAC provider and key
            _hmac     = parameters.getRight();
            _hmac_key = parameters.getMiddle();

            // Create the AES provider
            _inner    = new AesCbc.AesCbcDecryptor(parameters.getLeft(), iv, provider);

            _aad_length = toBigEndian(authenticationData.length * 8);
            
            // Save the tag
            _tag        = authenticationTag;

            // Prime the hash.
            _hmac.update(authenticationData);
            _hmac.update(iv);
        }
 
Example 3
Source File: AesCbcHmacSha2.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
AesCbcHmacSha2Encryptor(String name, byte[] key, byte[] iv, byte[] authenticationData, Provider provider) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException {
    // Split the key to get the AES key, the HMAC key and the HMAC
    // object
    Triple<byte[], byte[], Mac> parameters = GetAlgorithmParameters(name, key);

    // Save the MAC provider and key
    _hmac = parameters.getRight();
    _hmac_key = parameters.getMiddle();

    // Create the AES encryptor
    _inner = new AesCbc.AesCbcEncryptor(parameters.getLeft(), iv, provider);

    _aad_length = toBigEndian(authenticationData.length * 8);

    // Prime the hash.
    _hmac.update(authenticationData);
    _hmac.update(iv);
}
 
Example 4
Source File: SubmapManagerRCTM.java    From Chisel-2 with GNU General Public License v2.0 6 votes vote down vote up
@SideOnly(Side.CLIENT)
@SuppressWarnings("unchecked")
@Override
public void registerIcons(String modName, Block block, IIconRegister register) {
	IIcon base = register.registerIcon(modName + ":" + texturePath);
	int wh = (int) Math.sqrt(size);
	TextureSubmap[][] submaps = new TextureSubmap[wh][wh];
	TextureSubmap[][] submapsSmall = new TextureSubmap[wh][wh];
	for (int i = 0; i < size; i++) {
		AbstractSubmapManager manager = (AbstractSubmapManager) TextureType.CTMX.createManagerFor(CarvingUtils.getDefaultVariationFor(block, meta, 0), texturePath + "-" + i);
		manager.registerIcons(modName, block, register);
		Object cached = manager.getCachedObject();
		Triple<IIcon, TextureSubmap, TextureSubmap> triple = (Triple<IIcon, TextureSubmap, TextureSubmap>) cached;
		submaps[i % wh][i / wh] = triple.getMiddle();
		submapsSmall[i % wh][i / wh] = triple.getRight();
		if (i == 0) {
			defaultIcon = triple.getRight().getSubIcon(0, 0);
		}
	}
	submap = new Submap(base, wh, submaps);
	smallSubmap = new Submap(base, wh, submapsSmall);
}
 
Example 5
Source File: UrlTriePrefixGrouper.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Get the detailed pages under this group
 */
public static ArrayList<String> groupToPages(Triple<String, GoogleWebmasterFilter.FilterOperator, UrlTrieNode> group) {
  ArrayList<String> ret = new ArrayList<>();
  if (group.getMiddle().equals(GoogleWebmasterFilter.FilterOperator.EQUALS)) {
    if (group.getRight().isExist()) {
      ret.add(group.getLeft());
    }
  } else if (group.getMiddle().equals(GoogleWebmasterFilter.FilterOperator.CONTAINS)) {
    UrlTrie trie = new UrlTrie(group.getLeft(), group.getRight());
    Iterator<Pair<String, UrlTrieNode>> iterator = new UrlTriePostOrderIterator(trie, 1);
    while (iterator.hasNext()) {
      Pair<String, UrlTrieNode> next = iterator.next();
      if (next.getRight().isExist()) {
        ret.add(next.getLeft());
      }
    }
  }
  return ret;
}
 
Example 6
Source File: LineRegexReplaceInRegionBolt.java    From cognition with Apache License 2.0 5 votes vote down vote up
String replaceAll(String record) {
  for (Triple<Pattern, String, String> entry : groupSearchReplaceList) {
    Pattern pattern = entry.getLeft();
    String regex = entry.getMiddle();
    String replacement = entry.getRight();

    record = replace(record, pattern, regex, replacement);
  }
  return record;
}
 
Example 7
Source File: TicketHelper.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
private Triple<ValidationResult, Event, Ticket> assignTicket(UpdateTicketOwnerForm updateTicketOwner,
                                                             Optional<Errors> bindingResult,
                                                             Locale fallbackLocale,
                                                             Optional<UserDetails> userDetails,
                                                             Triple<Event, TicketReservation, Ticket> result,
                                                             String formPrefix) {
    Ticket t = result.getRight();
    final Event event = result.getLeft();
    if(t.getLockedAssignment()) {
        //in case of locked assignment, fullName and Email will be overwritten
        updateTicketOwner.setFirstName(t.getFirstName());
        updateTicketOwner.setLastName(t.getLastName());
        updateTicketOwner.setFullName(t.getFullName());
        updateTicketOwner.setEmail(t.getEmail());
    }

    final TicketReservation ticketReservation = result.getMiddle();
    List<TicketFieldConfiguration> fieldConf = ticketFieldRepository.findAdditionalFieldsForEvent(event.getId());
    var sameCountryValidator = new SameCountryValidator(configurationManager, extensionManager, event, ticketReservation.getId(), vatChecker);
    AdvancedTicketAssignmentValidator advancedValidator = new AdvancedTicketAssignmentValidator(sameCountryValidator,
        new GroupManager.WhitelistValidator(event.getId(), groupManager));


    var additionalServiceIds = new HashSet<>(additionalServiceItemRepository.findAdditionalServiceIdsByReservationUuid(t.getTicketsReservationId()));

    var ticketFieldFilterer = new Validator.TicketFieldsFilterer(fieldConf, ticketUUID -> t.getCategoryId(), additionalServiceIds, ticketRepository.findFirstTicketInReservation(t.getTicketsReservationId()));

    Validator.AdvancedValidationContext context = new Validator.AdvancedValidationContext(updateTicketOwner, fieldConf, t.getCategoryId(), t.getUuid(), formPrefix);
    ValidationResult validationResult = Validator.validateTicketAssignment(updateTicketOwner, ticketFieldFilterer.getFieldsForTicket(t.getUuid()), bindingResult, event, formPrefix, sameCountryValidator)
            .or(Validator.performAdvancedValidation(advancedValidator, context, bindingResult.orElse(null)))
            .ifSuccess(() -> updateTicketOwner(updateTicketOwner, fallbackLocale, t, event, ticketReservation, userDetails));
    return Triple.of(validationResult, event, ticketRepository.findByUUID(t.getUuid()));
}
 
Example 8
Source File: LearnReadOrientationModelEngine.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Given the posterior distributions over the artifact states (ie responsibilities) under the current estimates for the prior,
 * update the prior weights such that they maximize the lower bound on the marginal likelihood P(Data).
 * We do so by maximizing the expectation of the complete data likelihood with respect to the posterior
 * for the artifact states from the E-step
 */
private double[] takeMstep(final double[] pseudocounts) {
    // First we compute the effective counts of each state, N_k in the docs. We do this separately over alt and ref sites
    final double[] effectiveAltCountsFromDesignMatrix = MathUtils.sumArrayFunction(0, altDesignMatrix.size(), n -> altResponsibilities.getRow(n));
    double[] effectiveAltCountsFromHistograms = new double[F1R2FilterConstants.NUM_STATES];

    for (Histogram<Integer> histogram : altDepthOneHistograms){
        final Triple<String, Nucleotide, ReadOrientation> triplet = F1R2FilterUtils.labelToTriplet(histogram.getValueLabel());
        final Nucleotide altAllele = triplet.getMiddle();
        final ReadOrientation orientation = triplet.getRight();


        final double[] effectiveAltCountsFromHistogram = MathUtils.sumArrayFunction(0, maxDepth,
                i -> MathArrays.scale(histogram.get(i + 1).getValue(), responsibilitiesOfAltDepth1Sites.get(createKey(i+1, altAllele, orientation))));
        effectiveAltCountsFromHistograms = MathArrays.ebeAdd(effectiveAltCountsFromHistograms, effectiveAltCountsFromHistogram);
    }

    final double[] effectiveAltCounts = MathArrays.ebeAdd(effectiveAltCountsFromDesignMatrix, effectiveAltCountsFromHistograms);

    // TODO: at some depth, the responsibilities must be 1 for z = HOM_REF and 0 for everything else, we could probably save some time there
    // Over ref sites, we have a histogram of sites over different depths. At each depth we simply multiply the responsibilities by the number of sites,
    // and sum them over all of depths. Because we cut off the depth histogram at {@code MAX_COVERAGE}, we underestimate the ref effective counts by design
    final double[] effectiveRefCounts = MathUtils.sumArrayFunction(0, maxDepth,
            i -> MathArrays.scale(refHistogram.get(i + 1).getValue(), refResponsibilities.getRow(i)));

    effectiveCounts = new ArrayRealVector(MathArrays.ebeAdd(effectiveAltCounts, effectiveRefCounts));
    return MathUtils.normalizeSumToOne(effectiveCounts.add(new ArrayRealVector(pseudocounts)).toArray());
}
 
Example 9
Source File: SqlgSqlExecutor.java    From sqlg with MIT License 5 votes vote down vote up
public static void executeDropQuery(
        SqlgGraph sqlgGraph,
        SchemaTableTree rootSchemaTableTree,
        LinkedList<SchemaTableTree> distinctQueryStack) {

    sqlgGraph.getTopology().threadWriteLock();
    List<Triple<DROP_QUERY, String, Boolean>> sqls = rootSchemaTableTree.constructDropSql(distinctQueryStack);
    for (Triple<DROP_QUERY, String, Boolean> sqlPair : sqls) {
        DROP_QUERY dropQuery = sqlPair.getLeft();
        String sql = sqlPair.getMiddle();
        Boolean addAdditionalPartitionHasContainer = sqlPair.getRight();
        switch (dropQuery) {
            case ALTER:
            case TRUNCATE:
                executeDropQuery(sqlgGraph, sql, new LinkedList<>(), false);
                break;
            case EDGE:
                LinkedList<SchemaTableTree> tmp = new LinkedList<>(distinctQueryStack);
                tmp.removeLast();
                executeDropQuery(sqlgGraph, sql, tmp, false);
                break;
            case NORMAL:
                executeDropQuery(sqlgGraph, sql, distinctQueryStack, addAdditionalPartitionHasContainer);
                break;
            default:
                throw new IllegalStateException("Unknown DROP_QUERY " + dropQuery.toString());
        }
    }
}
 
Example 10
Source File: SqlgStartupManager.java    From sqlg with MIT License 5 votes vote down vote up
private void extractIndices(DatabaseMetaData metadata,
                            String catalog,
                            String schema,
                            String table,
                            String label,
                            boolean isVertex) {

    String lastIndexName = null;
    IndexType lastIndexType = null;
    List<String> lastColumns = new LinkedList<>();
    List<Triple<String, Boolean, String>> indexes = this.sqlDialect.getIndexInfo(metadata, catalog, schema, table, false, true);
    for (Triple<String, Boolean, String> index : indexes) {

        String indexName = index.getLeft();
        boolean nonUnique = index.getMiddle();
        String columnName = index.getRight();

        if (lastIndexName == null) {
            lastIndexName = indexName;
            lastIndexType = nonUnique ? IndexType.NON_UNIQUE : IndexType.UNIQUE;
        } else if (!lastIndexName.equals(indexName)) {
            if (!this.sqlDialect.isSystemIndex(lastIndexName)) {
                if (!Schema.GLOBAL_UNIQUE_INDEX_SCHEMA.equals(schema)) {
                    TopologyManager.addIndex(sqlgGraph, schema, label, isVertex, lastIndexName, lastIndexType, lastColumns);
                }
            }
            lastColumns.clear();
            lastIndexName = indexName;
            lastIndexType = nonUnique ? IndexType.NON_UNIQUE : IndexType.UNIQUE;
        }
        lastColumns.add(columnName);
    }
    if (!this.sqlDialect.isSystemIndex(lastIndexName)) {
        if (!Schema.GLOBAL_UNIQUE_INDEX_SCHEMA.equals(schema)) {
            TopologyManager.addIndex(sqlgGraph, schema, label, isVertex, lastIndexName, lastIndexType, lastColumns);
        }
    }
}
 
Example 11
Source File: Reddit.java    From Slide with GNU General Public License v3.0 5 votes vote down vote up
public void setupNotificationChannels() {
    if (SDK_INT >= android.os.Build.VERSION_CODES.O) {
        // Each triple contains the channel ID, name, and importance level
        List<Triple<String, String, Integer>> notificationTripleList =
                new ArrayList<Triple<String, String, Integer>>() {{
                    add(Triple.of(CHANNEL_IMG, "Image downloads",
                            NotificationManager.IMPORTANCE_LOW));
                    add(Triple.of(CHANNEL_COMMENT_CACHE, "Comment caching",
                            NotificationManager.IMPORTANCE_LOW));
                    add(Triple.of(CHANNEL_MAIL, "Reddit mail",
                            NotificationManager.IMPORTANCE_HIGH));
                    add(Triple.of(CHANNEL_MODMAIL, "Reddit modmail",
                            NotificationManager.IMPORTANCE_HIGH));
                    add(Triple.of(CHANNEL_SUBCHECKING, "Submission post checking",
                            NotificationManager.IMPORTANCE_LOW));
                }};

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        for (Triple<String, String, Integer> notificationTriple : notificationTripleList) {
            NotificationChannel notificationChannel =
                    new NotificationChannel(notificationTriple.getLeft(),
                            notificationTriple.getMiddle(), notificationTriple.getRight());
            notificationChannel.enableLights(true);
            notificationChannel.setShowBadge(
                    notificationTriple.getRight() == NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.setLightColor(
                    notificationTriple.getLeft().contains("MODMAIL") ? getResources().getColor(
                            R.color.md_red_500, null) : Palette.getColor(""));
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(notificationChannel);
            }
        }
    }
}
 
Example 12
Source File: GalleryInitResult.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
public int getParcelSize() {
    int total = 12;
    for (Triple<AttachmentModel, String, String> tuple : attachments) {
        total += 40;
        AttachmentModel attachment = tuple.getLeft();
        String hash = tuple.getMiddle();
        String post = tuple.getRight();
        if (attachment.thumbnail != null) total += attachment.thumbnail.length()*2;
        if (attachment.path != null) total += attachment.path.length()*2;
        if (attachment.originalName != null) total += attachment.originalName.length()*2;
        if (hash != null) total += hash.length()*2;
        if (post != null) total += post.length()*2;
    }
    return total;
}
 
Example 13
Source File: ItemBreakingTracker.java    From Survivalist with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void onItemBroken(PlayerEntity player, ItemStack stack)
{
    int scrappingLevel = EnchantmentHelper.getEnchantmentLevel(SurvivalistMod.SCRAPING.get(), stack);

    if (player.getClass().getName().equals("com.rwtema.extrautils2.fakeplayer.XUFakePlayer"))
        return;

    boolean fortune = rnd.nextDouble() > 0.9 / (1 + scrappingLevel);

    ItemStack ret = null;

    for (Triple<ItemStack, ItemStack, ItemStack> scraping : scrapingRegistry)
    {
        ItemStack source = scraping.getLeft();

        if (source.getItem() != stack.getItem())
            continue;

        ItemStack good = scraping.getMiddle();
        ItemStack bad = scraping.getRight();

        ret = fortune ? good.copy() : bad.copy();

        break;
    }

    if (ret != null)
    {
        SurvivalistMod.LOGGER.debug("Item broke (" + stack + ") and the player got " + ret + " in return!");

        SurvivalistMod.channel.sendTo(new ScrapingMessage(stack, ret), ((ServerPlayerEntity) player).connection.netManager, NetworkDirection.PLAY_TO_CLIENT);

        ItemHandlerHelper.giveItemToPlayer(player, ret);
    }
}
 
Example 14
Source File: EvaluationResult.java    From cineast with MIT License 5 votes vote down vote up
/**
 *
 * @return
 */
public final String toString(String delimiter) {
    StringBuilder builder = new StringBuilder();

    /* Create header. */
    builder.append("ID");
    builder.append(delimiter);
    builder.append("Hit");
    builder.append(delimiter);
    builder.append("Precision");
    builder.append(delimiter);
    builder.append("Recall");
    builder.append("\n");

    int i = 0;
    /* Append data. */
    for (Triple<String,Float,Float> triple : this.pk) {
        builder.append(triple.getLeft());
        builder.append(delimiter);

        /* Check if entry was a documentAvailable. */
        boolean hit = false;
        if (i == 0 && triple.getRight() > 0) {
            hit = true;
        } else if (i > 0 && triple.getRight() > this.pk.get(i-1).getRight()) {
            hit = true;
        }
        builder.append(hit ? 1 : 0);
        builder.append(delimiter);

        builder.append(triple.getMiddle());
        builder.append(delimiter);
        builder.append(triple.getRight());
        builder.append("\n");
        i++;
    }

    return builder.toString();
}
 
Example 15
Source File: IconVertexRangeUVTransform.java    From CodeChickenLib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Retrieves a TextureAtlasSprite from the internal map based on a vertex index.
 *
 * @param index The vertex index.
 * @return Returns the Icon, Null if no transform for the vertex index.
 */
public TextureAtlasSprite getSpriteForVertexIndex(int index) {
    for (Triple<Integer, Integer, TextureAtlasSprite> entry : transformMap) {
        if (MathHelper.between(entry.getLeft(), index, entry.getMiddle())) {
            return entry.getRight();
        }
    }
    return null;
}
 
Example 16
Source File: ConsulRegistryService.java    From saluki with Apache License 2.0 5 votes vote down vote up
private List<GrpcService> buildQueryResponse(Set<String> queryCondition, Boolean accurate) {
    List<GrpcService> services = Lists.newArrayList();
    Map<String, Pair<Set<GrpcHost>, Set<GrpcHost>>> servicesPassing = registryRepository.getAllPassingService();
    for (Iterator<String> it = queryCondition.iterator(); it.hasNext();) {
        String serviceKey = it.next();
        Triple<String, String, String> appNameServiceVersion = getAppNameServiceVersion(serviceKey);
        Pair<Set<GrpcHost>, Set<GrpcHost>> providerConsumer = servicesPassing.get(serviceKey);
        GrpcService service = new GrpcService(appNameServiceVersion.getLeft(), appNameServiceVersion.getRight(),
                                              appNameServiceVersion.getMiddle());
        service.setProviderHost(providerConsumer.getLeft());
        service.setConsumerHost(providerConsumer.getRight());
        services.add(service);
    }
    return services;
}
 
Example 17
Source File: StatisticService.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
public List<Statistic> createStatistic() {
	final List<Statistic> statisticList = statisticRepository.createStatistic();

	final Country favouriteCountry = getFavouriteCountry();
	final Map<String, Integer> favoriteCountryPointsPerUserMap = statisticRepository
			.sumPointsPerUserForFavoriteCountry(favouriteCountry);
	final Optional<Integer> maxFavoriteCountryPoints = favoriteCountryPointsPerUserMap.values().stream()
			.max(Comparator.comparing(i -> i));

	final Map<String, Integer> extraBetsPerUser = findExtraBetsPerUser();

	final Triple<Integer, Integer, Integer> triple = calculateMinMax(statisticList);
	final int minPoints = triple.getLeft();
	final int maxPoints = triple.getMiddle();
	final int maxGroupPoints = triple.getRight();

	for (Statistic statistic : statisticList) {
		statistic.setFavoriteCountry(favouriteCountry);

		final Integer favoriteCountryPoints = favoriteCountryPointsPerUserMap.get(statistic.getUsername());
		if (favoriteCountryPoints != null) {
			statistic.setPointsFavoriteCountry(favoriteCountryPoints);
			if (maxFavoriteCountryPoints.isPresent() && favoriteCountryPoints.equals(maxFavoriteCountryPoints.get())) {
				statistic.setMaxFavoriteCountryCandidate(true);
			}
		}

		statistic.setPointsForExtraBets(extraBetsPerUser.get(statistic.getUsername()));

		if (statistic.getSum() == minPoints) {
			statistic.setMinPointsCandidate(true);
		}
		if (statistic.getSum() == maxPoints) {
			statistic.setMaxPointsCandidate(true);
		}
		if (statistic.getPointsGroup() == maxGroupPoints) {
			statistic.setMaxGroupPointsCandidate(true);
		}
	}

	statisticList.sort(Comparator.comparing(Statistic::getUsername, String.CASE_INSENSITIVE_ORDER));
	return statisticList;
}
 
Example 18
Source File: FreeMarkerTemplateRendererBuilder.java    From youran with Apache License 2.0 4 votes vote down vote up
@Override
public TemplateRenderer buildRenderer(CodeTemplatePO templatePO) {
    Triple<Configuration, Integer, String> triple = freeMarkerConfigFactory.getConfigurationTriple(templatePO);
    FreeMarkerRenderer renderer = new FreeMarkerRenderer(triple.getLeft(), triple.getRight());
    return renderer;
}
 
Example 19
Source File: SqlgStartupManager.java    From sqlg with MIT License 4 votes vote down vote up
private void extractProperty(String schema, String table, String columnName, Integer columnType, String typeName, Map<String, PropertyType> columns, ListIterator<Triple<String, Integer, String>> metaDataIter) {
    //check for ZONEDDATETIME, PERIOD, DURATION as they use more than one field to represent the type
    PropertyType propertyType = null;
    if (metaDataIter.hasNext()) {
        Triple<String, Integer, String> column2MetaData = metaDataIter.next();
        String column2Name = column2MetaData.getLeft();
        String typeName2 = column2MetaData.getRight();
        int column2Type = column2MetaData.getMiddle();
        if (column2Name.startsWith(columnName + "~~~")) {
            if (column2Type == Types.VARCHAR) {
                propertyType = PropertyType.ZONEDDATETIME;
            } else if ((column2Type == Types.ARRAY && this.sqlDialect.sqlArrayTypeNameToPropertyType(typeName2, this.sqlgGraph, schema, table, column2Name, metaDataIter) == PropertyType.STRING_ARRAY)) {
                propertyType = PropertyType.ZONEDDATETIME_ARRAY;
            } else {
                if (metaDataIter.hasNext()) {
                    Triple<String, Integer, String> column3MetaData = metaDataIter.next();
                    String column3Name = column3MetaData.getLeft();
                    String typeName3 = column3MetaData.getRight();
                    int column3Type = column3MetaData.getMiddle();
                    if (column3Name.startsWith(columnName + "~~~")) {
                        if (column3Type == Types.ARRAY) {
                            Preconditions.checkState(sqlDialect.sqlArrayTypeNameToPropertyType(typeName3, this.sqlgGraph, schema, table, column3Name, metaDataIter) == PropertyType.INTEGER_ARRAY, "Only Period have a third column and it must be a Integer");
                            propertyType = PropertyType.PERIOD_ARRAY;
                        } else {
                            Preconditions.checkState(column3Type == Types.INTEGER, "Only Period have a third column and it must be a Integer");
                            propertyType = PropertyType.PERIOD;
                        }
                    } else {
                        metaDataIter.previous();
                        if (column2Type == Types.ARRAY) {
                            Preconditions.checkState(sqlDialect.sqlArrayTypeNameToPropertyType(typeName2, this.sqlgGraph, schema, table, column2Name, metaDataIter) == PropertyType.INTEGER_ARRAY, "Only Period have a third column and it must be a Integer");
                            propertyType = PropertyType.DURATION_ARRAY;
                        } else {
                            Preconditions.checkState(column2Type == Types.INTEGER, "Only Duration and Period have a second column and it must be a Integer");
                            propertyType = PropertyType.DURATION;
                        }
                    }
                }
            }
        } else {
            metaDataIter.previous();
        }
    }
    if (propertyType == null) {
        propertyType = this.sqlDialect.sqlTypeToPropertyType(this.sqlgGraph, schema, table, columnName, columnType, typeName, metaDataIter);
    }
    columns.put(columnName, propertyType);
}
 
Example 20
Source File: TxPoolV1.java    From aion with MIT License 4 votes vote down vote up
/**
 * @implNote snapshot the transactions for creating new block template.
 * @return the transactions ready to be seal into the new blocks.
 */
public List<AionTransaction> snapshot() {

    lock.lock();
    try {
        if (poolTransactions.isEmpty()) {
            return Collections.emptyList();
        }

        Map<AionAddress, BigInteger> accountPickingInfo = new HashMap<>();
        Set<ByteArrayWrapper> pickedTxHash = new HashSet<>();

        // We use the multi rounds picking strategy.
        List<AionTransaction> pickedTransactions = new ArrayList<>();
        int totalPicked;
        long cumulatedTxEncodedSize = 0;
        long cumulatedTxEnergyConsumed = 0;
        LOG_TXPOOL.info("Start to pick transaction");
        do {
            totalPicked = pickedTransactions.size();

            Triple<List<AionTransaction>, Long, Long> newPicked =
                    pickTransaction(
                            accountPickingInfo,
                            pickedTxHash,
                            cumulatedTxEncodedSize,
                            cumulatedTxEnergyConsumed);
            cumulatedTxEncodedSize += newPicked.getMiddle();
            cumulatedTxEnergyConsumed += newPicked.getRight();
            LOG_TXPOOL.debug(
                    "transaction picked: {}, newPickedEncodedSize: {}, newPickedEnergyConsumed: {}",
                    newPicked.getLeft().size(),
                    newPicked.getMiddle(),
                    newPicked.getRight());
            pickedTransactions.addAll(newPicked.getLeft());

        } while (totalPicked < pickedTransactions.size());

        LOG_TXPOOL.info(
                "snapshot {} tx, totalEncodedSize: {}, totalEnergyConsumed: {}",
                pickedTransactions.size(),
                cumulatedTxEncodedSize,
                cumulatedTxEnergyConsumed);
        return pickedTransactions;
    } finally {
        lock.unlock();
    }
}