Java Code Examples for org.apache.commons.lang3.tuple.Triple#of()
The following examples show how to use
org.apache.commons.lang3.tuple.Triple#of() .
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: StatisticService.java From fredbet with Creative Commons Attribution Share Alike 4.0 International | 6 votes |
private Triple<Integer, Integer, Integer> calculateMinMax(List<Statistic> statisticList) { int minPoints = Integer.MAX_VALUE; int maxPoints = 0; int maxGroupPoints = 0; for (Statistic statistic : statisticList) { if (statistic.getSum() < minPoints) { minPoints = statistic.getSum(); } if (statistic.getSum() > maxPoints) { maxPoints = statistic.getSum(); } if (statistic.getPointsGroup() > maxGroupPoints) { maxGroupPoints = statistic.getPointsGroup(); } } return Triple.of(minPoints, maxPoints, maxGroupPoints); }
Example 2
Source File: UrlTriePrefixGrouper.java From incubator-gobblin with Apache License 2.0 | 6 votes |
@Override public boolean hasNext() { if (_retVal != null) { return true; } while (_iterator.hasNext() && _retVal == null) { Pair<String, UrlTrieNode> nextPair = _iterator.next(); UrlTrieNode nextNode = nextPair.getRight(); if (nextNode.getSize() <= _groupSize) { _retVal = Triple.of(nextPair.getLeft(), GoogleWebmasterFilter.FilterOperator.CONTAINS, nextNode); return true; } else if (nextNode.isExist()) { _retVal = Triple.of(nextPair.getLeft(), GoogleWebmasterFilter.FilterOperator.EQUALS, nextNode); return true; } } return false; }
Example 3
Source File: SAFA.java From symbolicautomata with Apache License 2.0 | 5 votes |
/** * Computes the intersection with <code>aut1</code> and <code>aut2</code> as * a new SFA * @throws TimeoutException */ public static <A, B> Triple<SAFA<A, B>, PositiveBooleanExpression,PositiveBooleanExpression> binaryOp(SAFA<A, B> aut1, SAFA<A, B> aut2, BooleanAlgebra<A, B> ba, BoolOp op) throws TimeoutException { int offset = aut1.maxStateId + 1; BooleanExpressionFactory<PositiveBooleanExpression> boolexpr = getBooleanExpressionFactory(); // Integer initialState = aut1.maxStateId + aut2.maxStateId + 2; PositiveBooleanExpression initialState = null; Collection<Integer> finalStates = new ArrayList<Integer>(aut1.finalStates); for (int state : aut2.finalStates) finalStates.add(state + offset); // Copy all transitions (with proper renaming for aut2) Collection<SAFAInputMove<A, B>> transitions = new ArrayList<SAFAInputMove<A, B>>(aut1.getInputMoves()); for (SAFAInputMove<A, B> t : aut2.getInputMoves()) transitions.add(new SAFAInputMove<>(t.from + offset, boolexpr.offset(offset).apply(t.to), t.guard)); PositiveBooleanExpression liftedAut2Init = boolexpr.offset(offset).apply(aut2.initialState); switch (op) { case Union: initialState = boolexpr.MkOr(aut1.initialState, liftedAut2Init); break; case Intersection: // Add extra moves from new initial state initialState = boolexpr.MkAnd(aut1.initialState, liftedAut2Init); break; default: throw new NotImplementedException("Operation " + op + " not implemented"); } return Triple.of( MkSAFA(transitions, initialState, finalStates, ba, false, false, false), aut1.initialState, liftedAut2Init); }
Example 4
Source File: TicketHelper.java From alf.io with GNU General Public License v3.0 | 5 votes |
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 5
Source File: NetconfDeviceInfo.java From onos with Apache License 2.0 | 5 votes |
public static Triple<String, Integer, Optional<String>> extractIpPortPath(DeviceId deviceId) { /* * We can expect the following formats: * * netconf:ip:port/path * netconf:ip:port */ String string = deviceId.toString(); /* * The first ':' is the separation between the scheme and the IP. * * The last ':' will represent the separator between the IP and the port. */ int first = string.indexOf(':'); int last = string.lastIndexOf(':'); String ip = string.substring(first + 1, last); String port = string.substring(last + 1); String path = null; int pathSep = port.indexOf('/'); if (pathSep != -1) { path = port.substring(pathSep + 1); port = port.substring(0, pathSep); } return Triple.of(ip, new Integer(port), (path == null || path.isEmpty() ? Optional.empty() : Optional.of(path))); }
Example 6
Source File: TaskLogic.java From syncope with Apache License 2.0 | 5 votes |
@Override protected Triple<JobType, String, String> getReference(final JobKey jobKey) { String key = JobNamer.getTaskKeyFromJobName(jobKey.getName()); Task task = taskDAO.find(key); return task == null || !(task instanceof SchedTask) ? null : Triple.of(JobType.TASK, key, binder.buildRefDesc(task)); }
Example 7
Source File: DashboardOverviewPanel.java From syncope with Apache License 2.0 | 5 votes |
private static Triple<Integer, String, String> buildTotalAny2OrResources(final NumbersInfo numbers) { int number; String label; String icon; if (numbers.getAnyType2() == null) { number = numbers.getTotalResources(); label = new ResourceModel("resources").getObject(); icon = "fa fa-database"; } else { number = numbers.getTotalAny2(); label = numbers.getAnyType2(); icon = "ion ion-gear-a"; } return Triple.of(number, label, icon); }
Example 8
Source File: DashboardOverviewPanel.java From syncope with Apache License 2.0 | 5 votes |
private static Triple<Integer, String, String> buildTotalAny1OrRoles(final NumbersInfo numbers) { int number; String label; String icon; if (numbers.getAnyType1() == null) { number = numbers.getTotalRoles(); label = new ResourceModel("roles").getObject(); icon = "fa fa-users"; } else { number = numbers.getTotalAny1(); label = numbers.getAnyType1(); icon = "ion ion-gear-a"; } return Triple.of(number, label, icon); }
Example 9
Source File: FreeMarkerConfigFactory.java From youran with Apache License 2.0 | 5 votes |
/** * 构建freemarker配置 * * @param templatePO * @return (freemarker配置 , 模板内部版本号 , 模板目录地址) */ private Triple<Configuration, Integer, String> buildTriple(CodeTemplatePO templatePO) { String templateDir = dataDirService.getTemplateRecentDir(templatePO); LOGGER.info("开始构建FreeMarker Configuration,templateId={},innerVersion={},模板文件输出目录:{}", templatePO.getTemplateId(), templatePO.getInnerVersion(), templateDir); // 把模板输出到目录 templateFileOutputService.outputTemplateFiles(templatePO.getTemplateFiles(), templateDir); Configuration cfg = new Configuration(Configuration.VERSION_2_3_25); try { cfg.setDirectoryForTemplateLoading(new File(templateDir)); } catch (IOException e) { LOGGER.error("模板目录设置异常", e); throw new BusinessException("模板目录设置异常"); } cfg.setNumberFormat("#"); // 设置可访问的静态工具类 cfg.setSharedVariable("MetaConstType", metaConstTypeModel); cfg.setSharedVariable("JFieldType", jFieldTypeModel); cfg.setSharedVariable("QueryType", queryTypeModel); cfg.setSharedVariable("EditType", editTypeModel); cfg.setSharedVariable("MetaSpecialField", metaSpecialFieldModel); cfg.setSharedVariable("PrimaryKeyStrategy", primaryKeyStrategyModel); cfg.setSharedVariable("CommonTemplateFunction", commonTemplateFunctionModel); cfg.setSharedVariable("JavaTemplateFunction", javaTemplateFunctionModel); cfg.setSharedVariable("SqlTemplateFunction", sqlTemplateFunctionModel); return Triple.of(cfg, templatePO.getInnerVersion(), templateDir); }
Example 10
Source File: AdminReservationManagerIntegrationTest.java From alf.io with GNU General Public License v3.0 | 5 votes |
private Triple<Event, String, TicketReservation> performExistingCategoryTest(List<TicketCategoryModification> categories, boolean bounded, List<Integer> attendeesNr, boolean addSeatsIfNotAvailable, boolean expectSuccess, int reservedTickets, int expectedEventSeats) { assertEquals("Test error: categories' size must be equal to attendees' size", categories.size(), attendeesNr.size()); Pair<Event, String> eventWithUsername = initEvent(categories, organizationRepository, userManager, eventManager, eventRepository); Event event = eventWithUsername.getKey(); String username = eventWithUsername.getValue(); DateTimeModification expiration = DateTimeModification.fromZonedDateTime(ZonedDateTime.now().plusDays(1)); CustomerData customerData = new CustomerData("Integration", "Test", "[email protected]", "Billing Address", "reference", "en", "1234", "CH", null); Iterator<Integer> attendeesIterator = attendeesNr.iterator(); List<TicketCategory> existingCategories = ticketCategoryRepository.findAllTicketCategories(event.getId()); List<Attendee> allAttendees = new ArrayList<>(); List<TicketsInfo> ticketsInfoList = existingCategories.stream() .map(existingCategory -> { Category category = new Category(existingCategory.getId(), existingCategory.getName(), existingCategory.getPrice()); List<Attendee> attendees = generateAttendees(attendeesIterator.next()); allAttendees.addAll(attendees); return new TicketsInfo(category, attendees, addSeatsIfNotAvailable, false); }).collect(toList()); AdminReservationModification modification = new AdminReservationModification(expiration, customerData, ticketsInfoList, "en", false,false, null, null); if(reservedTickets > 0) { TicketReservationModification trm = new TicketReservationModification(); trm.setAmount(reservedTickets); trm.setTicketCategoryId(existingCategories.get(0).getId()); TicketReservationWithOptionalCodeModification r = new TicketReservationWithOptionalCodeModification(trm, Optional.empty()); ticketReservationManager.createTicketReservation(event, Collections.singletonList(r), Collections.emptyList(), DateUtils.addDays(new Date(), 1), Optional.empty(), Locale.ENGLISH, false); } Result<Pair<TicketReservation, List<Ticket>>> result = adminReservationManager.createReservation(modification, event.getShortName(), username); if(expectSuccess) { validateSuccess(bounded, attendeesNr, event, username, existingCategories, result, allAttendees, expectedEventSeats, reservedTickets); } else { assertFalse(result.isSuccess()); return null; } return Triple.of(eventWithUsername.getLeft(), eventWithUsername.getRight(), result.getData().getKey()); }
Example 11
Source File: SqlgUtil.java From sqlg with MIT License | 5 votes |
/** * Validates the key values and converts it into a Triple with three maps. * The left map is a map of keys together with their PropertyType. * The middle map is a map of keys together with their values. * The right map is a map of keys with values where the values are guaranteed not to be null. * * @param sqlDialect The dialect. * @param keyValues The key value pairs. * @return A Triple with 3 maps. */ public static Triple<Map<String, PropertyType>, Map<String, Object>, Map<String, Object>> validateVertexKeysValues(SqlDialect sqlDialect, Object[] keyValues) { Map<String, Object> resultAllValues = new LinkedHashMap<>(); Map<String, Object> resultNotNullValues = new LinkedHashMap<>(); Map<String, PropertyType> keyPropertyTypeMap = new LinkedHashMap<>(); if (keyValues.length % 2 != 0) throw Element.Exceptions.providedKeyValuesMustBeAMultipleOfTwo(); for (int i = 0; i < keyValues.length; i = i + 2) { if (!(keyValues[i] instanceof String) && !(keyValues[i] instanceof T)) { throw Element.Exceptions.providedKeyValuesMustHaveALegalKeyOnEvenIndices(); } if (keyValues[i].equals(T.id)) { throw Vertex.Exceptions.userSuppliedIdsNotSupported(); } if (!keyValues[i].equals(T.label)) { String key = (String) keyValues[i]; sqlDialect.validateColumnName(key); Object value = keyValues[i + 1]; ElementHelper.validateProperty(key, value); sqlDialect.validateProperty(key, value); if (value != null) { resultNotNullValues.put(key, value); keyPropertyTypeMap.put(key, PropertyType.from(value)); } else { keyPropertyTypeMap.put(key, PropertyType.STRING); } resultAllValues.put(key, value); } } return Triple.of(keyPropertyTypeMap, resultAllValues, resultNotNullValues); }
Example 12
Source File: AionBlockchainImpl.java From aion with MIT License | 5 votes |
/** * Imports a batch of blocks. * * @param blockRange the block range to be imported * @param peerDisplayId the display identifier for the peer who provided the batch * @return a {@link Triple} containing: * <ol> * <li>the best block height after the imports,</li> * <li>the set of imported hashes,</li> * <li>the import result for the last imported block</li> * </ol> */ public Triple<Long, Set<ByteArrayWrapper>, ImportResult> tryToConnect(final List<Block> blockRange, String peerDisplayId) { lock.lock(); try { ImportResult importResult = null; Set<ByteArrayWrapper> imported = new HashSet<>(); for (Block block : blockRange) { Pair<ImportResult, Long> result = tryToConnectWithTimedExecution(new BlockWrapper(block)); importResult = result.getLeft(); long importTime = result.getRight(); // printing additional information when debug is enabled SYNC_LOG.debug( "<import-status: node = {}, hash = {}, number = {}, txs = {}, block time = {}, result = {}, time elapsed = {} ns, block td = {}, chain td = {}>", peerDisplayId, block.getShortHash(), block.getNumber(), block.getTransactionsList().size(), block.getTimestamp(), importResult, importTime, block.getTotalDifficulty(), getTotalDifficulty()); if (checkKernelShutdownForCLI()) { break; } else if (!importResult.isStored()) { // stop at invalid blocks return Triple.of(bestBlock.getNumber(), imported, importResult); } else { imported.add(block.getHashWrapper()); } } return Triple.of(bestBlock.getNumber(), imported, importResult); } finally{ lock.unlock(); checkKernelExit(); } }
Example 13
Source File: KeyDepotServiceImpl.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
@Override public Set<EncryptionToken> getETKSet(org.taktik.connector.technical.utils.IdentifierType identifierType, String identifierValue, String applicationId, UUID longLivedCacheKey, boolean isOwnEtk) throws TechnicalConnectorException { Date now = new Date(); Triple<IdentifierType, String, String> key = Triple.of(identifierType, identifierValue, applicationId); Set<EncryptionToken> cachedResult = longLivedCacheKey != null ? longLivedEtksMap.get(Pair.of(longLivedCacheKey, key)) : null; if (cachedResult == null) { cachedResult = etksMap.get(key); if (cachedResult != null && isOwnEtk && longLivedCacheKey != null) { longLivedEtksMap.put(Pair.of(longLivedCacheKey, key), cachedResult); } } if (cachedResult == null || !cachedResult.stream().allMatch(tok -> tok.getCertificate().getNotAfter().after(now))) { Set<EncryptionToken> result = new HashSet<>(); SearchCriteriaType searchCriteria = this.generatedSearchCriteria(identifierType.getType(ETKDEPOT), identifierValue, applicationId); GetEtkResponse response = this.getETK(searchCriteria); validate(response); if (response.getETK() != null) { result.add(toEncryptionToken(response.getETK())); } else if (applicationId == null && !response.getMatchingEtks().isEmpty()) { for (MatchingEtk matchEtk : response.getMatchingEtks()) { result.addAll(this.getEtk(matchEtk, identifierType, identifierValue)); } } else { unableToFindEtk(searchCriteria); } if (isOwnEtk && longLivedCacheKey != null) { longLivedEtksMap.put(Pair.of(longLivedCacheKey, key), result); } else { etksMap.put(key, result); } return result; } return cachedResult; }
Example 14
Source File: SqlgSqlExecutor.java From sqlg with MIT License | 4 votes |
private static Triple<ResultSet, ResultSetMetaData, PreparedStatement> executeQuery(SqlgGraph sqlgGraph, String sql, LinkedList<SchemaTableTree> distinctQueryStack) { if (sqlgGraph.tx().isInBatchMode()) { sqlgGraph.tx().flush(); } try { if (distinctQueryStack.peekFirst().getStepType() != SchemaTableTree.STEP_TYPE.GRAPH_STEP) { Preconditions.checkState(!distinctQueryStack.peekFirst().getParentIdsAndIndexes().isEmpty()); } Connection conn = sqlgGraph.tx().getConnection(); if (logger.isDebugEnabled()) { logger.debug(sql); } // explain plan can be useful for performance issues // uncomment if needed, don't think we need this in production // if (logger.isTraceEnabled()){ // String expl="EXPLAIN "+sql; // try { // try (PreparedStatement stmt=conn.prepareStatement(expl)){ // int parameterCount = 1; // if (recordId != null) { // stmt.setLong(parameterCount++, recordId.getId()); // } // SqlgUtil.setParametersOnStatement(sqlgGraph, distinctQueryStack, conn, stmt, parameterCount); // try(ResultSet rs=stmt.executeQuery()){ // while(rs.next()){ // System.out.println(rs.getString(1)); // } // } // // // } // } catch (SQLException sqle){ // logger.warn(expl); // logger.warn(sqle.getMessage()); // } // } PreparedStatement preparedStatement = conn.prepareStatement(sql); sqlgGraph.tx().add(preparedStatement); int parameterCount = 1; SqlgUtil.setParametersOnStatement(sqlgGraph, distinctQueryStack, preparedStatement, parameterCount); // https://jdbc.postgresql.org/documentation/head/query.html#query-with-cursor // this is critical to use a cursor, otherwise we load everything into memory if (sqlgGraph.tx().getFetchSize()!=null){ preparedStatement.setFetchSize(sqlgGraph.tx().getFetchSize()); } ResultSet resultSet = preparedStatement.executeQuery(); ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); return Triple.of(resultSet, resultSetMetaData, preparedStatement); } catch (SQLException e) { throw new RuntimeException(e); } }
Example 15
Source File: AesCbcHmacSha2.java From azure-keyvault-java with MIT License | 4 votes |
private static Triple<byte[], byte[], Mac> GetAlgorithmParameters(String algorithm, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException { byte[] aes_key; byte[] hmac_key; Mac hmac; if (algorithm.equalsIgnoreCase(Aes128CbcHmacSha256.ALGORITHM_NAME)) { if ((key.length << 3) < 256) { throw new IllegalArgumentException(String.format("%s key length in bits %d < 256", algorithm, key.length << 3)); } hmac_key = new byte[128 >> 3]; aes_key = new byte[128 >> 3]; // The HMAC key precedes the AES key System.arraycopy(key, 0, hmac_key, 0, 128 >> 3); System.arraycopy(key, 128 >> 3, aes_key, 0, 128 >> 3); hmac = Mac.getInstance("HmacSHA256"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256")); } else if (algorithm.equalsIgnoreCase(Aes192CbcHmacSha384.ALGORITHM_NAME)) { if ((key.length << 3) < 384) { throw new IllegalArgumentException(String.format("%s key length in bits %d < 384", algorithm, key.length << 3)); } hmac_key = new byte[192 >> 3]; aes_key = new byte[192 >> 3]; // The HMAC key precedes the AES key System.arraycopy(key, 0, hmac_key, 0, 192 >> 3); System.arraycopy(key, 192 >> 3, aes_key, 0, 192 >> 3); hmac = Mac.getInstance("HmacSHA384"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA384")); } else if (algorithm.equalsIgnoreCase(Aes256CbcHmacSha512.ALGORITHM_NAME)) { if ((key.length << 3) < 512) { throw new IllegalArgumentException(String.format("%s key length in bits %d < 512", algorithm, key.length << 3)); } hmac_key = new byte[256 >> 3]; aes_key = new byte[256 >> 3]; // The HMAC key precedes the AES key System.arraycopy(key, 0, hmac_key, 0, 256 >> 3); System.arraycopy(key, 256 >> 3, aes_key, 0, 256 >> 3); hmac = Mac.getInstance("HmacSHA512"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA512")); } else { throw new IllegalArgumentException(String.format("Unsupported algorithm: %s", algorithm)); } return Triple.of(aes_key, hmac_key, hmac); }
Example 16
Source File: AbstractAnySearchDAO.java From syncope with Apache License 2.0 | 4 votes |
protected Triple<PlainSchema, PlainAttrValue, AnyCond> check(final AnyCond cond, final AnyTypeKind kind) { AnyCond computed = new AnyCond(cond.getType()); computed.setSchema(cond.getSchema()); computed.setExpression(cond.getExpression()); AnyUtils anyUtils = anyUtilsFactory.getInstance(kind); Field anyField = anyUtils.getField(computed.getSchema()); if (anyField == null) { LOG.warn("Ignoring invalid field '{}'", computed.getSchema()); throw new IllegalArgumentException(); } // Keeps track of difference between entity's getKey() and JPA @Id fields if ("key".equals(computed.getSchema())) { computed.setSchema("id"); } PlainSchema schema = entityFactory.newEntity(PlainSchema.class); schema.setKey(anyField.getName()); for (AttrSchemaType attrSchemaType : AttrSchemaType.values()) { if (anyField.getType().isAssignableFrom(attrSchemaType.getType())) { schema.setType(attrSchemaType); } } // Deal with any Integer fields logically mapping to boolean values boolean foundBooleanMin = false; boolean foundBooleanMax = false; if (Integer.class.equals(anyField.getType())) { for (Annotation annotation : anyField.getAnnotations()) { if (Min.class.equals(annotation.annotationType())) { foundBooleanMin = ((Min) annotation).value() == 0; } else if (Max.class.equals(annotation.annotationType())) { foundBooleanMax = ((Max) annotation).value() == 1; } } } if (foundBooleanMin && foundBooleanMax) { schema.setType(AttrSchemaType.Boolean); } // Deal with any fields representing relationships to other entities if (ArrayUtils.contains(RELATIONSHIP_FIELDS, computed.getSchema())) { computed.setSchema(computed.getSchema() + "_id"); schema.setType(AttrSchemaType.String); } PlainAttrValue attrValue = anyUtils.newPlainAttrValue(); if (computed.getType() != AttrCond.Type.LIKE && computed.getType() != AttrCond.Type.ILIKE && computed.getType() != AttrCond.Type.ISNULL && computed.getType() != AttrCond.Type.ISNOTNULL) { try { ((JPAPlainSchema) schema).validator().validate(computed.getExpression(), attrValue); } catch (ValidationException e) { LOG.error("Could not validate expression '" + computed.getExpression() + '\'', e); throw new IllegalArgumentException(); } } return Triple.of(schema, attrValue, computed); }
Example 17
Source File: TxPoolV1.java From aion with MIT License | 4 votes |
private Triple<List<AionTransaction>, Long, Long> pickTransaction( Map<AionAddress, BigInteger> accountPickingInfo, Set<ByteArrayWrapper> pickedTxHash, long cumulatedTxEncodedSize, long cumulatedTxEnergy) { List<AionTransaction> pickedTx = new ArrayList<>(); long pickedTxEncodedSize = 0; long pickedEnergyConsumed = 0; for (Set<ByteArrayWrapper> s : feeView.values()) { for (ByteArrayWrapper hash : s) { if (!pickedTxHash.contains(hash)) { PooledTransaction pendingTx = poolTransactions.get(hash); AionAddress sender = pendingTx.tx.getSenderAddress(); BigInteger currentAccountPickingNonce = accountPickingInfo.getOrDefault(sender, getAccountFirstPickingNonce(sender)); if (currentAccountPickingNonce.equals(pendingTx.tx.getNonceBI())) { long txEncodedSize = pendingTx.tx.getEncoded().length; long txEnergyConsumed = Math.max(pendingTx.energyConsumed, (Constant.MIN_ENERGY_CONSUME / 2)); if ((cumulatedTxEncodedSize + pickedTxEncodedSize + txEncodedSize) <= Constant.MAX_BLK_SIZE && (cumulatedTxEnergy + pickedEnergyConsumed + txEncodedSize) <= blockEnergyLimit) { LOG_TXPOOL.trace("Transaction picked: [{}]", pendingTx.tx); pickedTx.add(pendingTx.tx); pickedTxHash.add(hash); currentAccountPickingNonce = currentAccountPickingNonce.add(BigInteger.ONE); accountPickingInfo.put(sender, currentAccountPickingNonce); pickedTxEncodedSize += txEncodedSize; pickedEnergyConsumed += txEnergyConsumed; } else { return Triple.of(pickedTx, pickedTxEncodedSize, pickedEnergyConsumed); } } } } } return Triple.of(pickedTx, pickedTxEncodedSize, pickedEnergyConsumed); }
Example 18
Source File: NotificationLogic.java From syncope with Apache License 2.0 | 4 votes |
@Override protected Triple<JobType, String, String> getReference(final JobKey jobKey) { return JobManager.NOTIFICATION_JOB.equals(jobKey) ? Triple.of(JobType.NOTIFICATION, (String) null, NotificationJob.class.getSimpleName()) : null; }
Example 19
Source File: VcfFuncotationFactory.java From gatk with BSD 3-Clause "New" or "Revised" License | 4 votes |
private Triple<VariantContext, ReferenceContext, List<Feature>> createCacheKey(final VariantContext variant, final ReferenceContext referenceContext, final List<Feature> featureList) { return Triple.of(variant, referenceContext, featureList); }
Example 20
Source File: TicketReservationManagerIntegrationTest.java From alf.io with GNU General Public License v3.0 | 4 votes |
private Triple<Event, TicketCategory, String> testTicketsWithAccessCode() { List<TicketCategoryModification> categories = Collections.singletonList( new TicketCategoryModification(null, "default", AVAILABLE_SEATS, new DateTimeModification(LocalDate.now(), LocalTime.now()), new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN, true, "", true, null, null, null, null, null, 0, null, null, AlfioMetadata.empty())); Event event = initEvent(categories, organizationRepository, userManager, eventManager, eventRepository).getKey(); TicketCategory category = ticketCategoryRepository.findAllTicketCategories(event.getId()).stream().filter(TicketCategory::isAccessRestricted).findFirst().orElseThrow(); specialPriceTokenGenerator.generatePendingCodesForCategory(category.getId()); //promo code at event level String accessCode = ACCESS_CODE; eventManager.addPromoCode(accessCode, event.getId(), null, event.getBegin(), event.getEnd(), 0, null, null, 3, "description", "[email protected]", PromoCodeDiscount.CodeType.ACCESS, category.getId()); TicketReservationModification tr = new TicketReservationModification(); tr.setAmount(3); tr.setTicketCategoryId(category.getId()); TicketReservationWithOptionalCodeModification mod = new TicketReservationWithOptionalCodeModification(tr, Optional.empty()); String reservationId = ticketReservationManager.createTicketReservation(event, Collections.singletonList(mod), Collections.emptyList(), DateUtils.addDays(new Date(), 1), Optional.of(accessCode), Locale.ENGLISH, false); Pair<TotalPrice, Optional<PromoCodeDiscount>> priceAndDiscount = ticketReservationManager.totalReservationCostWithVAT(reservationId); TotalPrice totalPrice = priceAndDiscount.getLeft(); assertFalse(priceAndDiscount.getRight().isEmpty()); assertEquals(ACCESS_CODE, priceAndDiscount.getRight().get().getPromoCode()); // 3 * 10 chf is the normal price, 10% discount -> 300 discount Assert.assertEquals(3000, totalPrice.getPriceWithVAT()); Assert.assertEquals(30, totalPrice.getVAT()); Assert.assertEquals(0, totalPrice.getDiscount()); Assert.assertEquals(0, totalPrice.getDiscountAppliedCount()); OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId, event); Assert.assertEquals("30.00", orderSummary.getTotalPrice()); Assert.assertEquals("0.30", orderSummary.getTotalVAT()); Assert.assertEquals(3, orderSummary.getTicketAmount()); return Triple.of(event, category, reservationId); }