类org.apache.commons.lang3.tuple.Triple源码实例Demo

下面列出了怎么用org.apache.commons.lang3.tuple.Triple的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: airsonic-advanced   文件: SonosLinkController.java
@PostMapping
public ModelAndView doPost(HttpServletRequest request) {
    String linkCode = request.getParameter("linkCode");
    String username = request.getParameter("j_username");
    String password = request.getParameter("j_password");

    Triple<String, String, Instant> data = sonosService.getInitiatedLinkCodeData(linkCode);
    if (data == null) {
        return new ModelAndView("sonosLinkFailure", "model", Map.of("linkCode", linkCode, "errorCode", "sonos.linkcode.notfound"));
    }

    try {
        Authentication authenticate = authManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        if (authenticate.isAuthenticated()) {
            if (sonosService.addSonosAuthorization(username, linkCode, data.getLeft(), data.getMiddle(), data.getRight())) {
                return new ModelAndView("sonosSuccess", "model", Collections.emptyMap());
            } else {
                return new ModelAndView("sonosLinkFailure", "model", Map.of("linkCode", linkCode, "errorCode", "sonos.linkcode.alreadyused"));
            }
        } else {
            return loginFailed(linkCode);
        }
    } catch (BadCredentialsException e) {
        return loginFailed(linkCode);
    }
}
 
源代码2 项目: sqlg   文件: SqlgGraph.java
private SqlgVertex internalStreamVertex(Object... keyValues) {
    Preconditions.checkState(this.sqlDialect.supportsStreamingBatchMode(), "Streaming batch mode is not supported.");
    final String label = ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL);
    SchemaTable schemaTablePair = SchemaTable.from(this, label);

    SchemaTable streamingBatchModeVertexSchemaTable = this.tx().getBatchManager().getStreamingBatchModeVertexSchemaTable();
    if (streamingBatchModeVertexSchemaTable != null && !streamingBatchModeVertexSchemaTable.toString().equals(schemaTablePair.toString())) {
        throw new IllegalStateException("Streaming batch mode must occur for one label at a time. Expected \"" + streamingBatchModeVertexSchemaTable + "\" found \"" + label + "\". First commit the transaction or call SqlgGraph.flush() before streaming a different label");
    }
    List<String> keys = this.tx().getBatchManager().getStreamingBatchModeVertexKeys();
    Triple<Map<String, PropertyType>, Map<String, Object>, Map<String, Object>> keyValueMapTriple = SqlgUtil.validateVertexKeysValues(this.sqlDialect, keyValues, keys);
    final Pair<Map<String, Object>, Map<String, Object>> keyValueMapPair = Pair.of(keyValueMapTriple.getMiddle(), keyValueMapTriple.getRight());
    final Map<String, PropertyType> columns = keyValueMapTriple.getLeft();
    this.tx().readWrite();
    this.getTopology().ensureVertexLabelExist(schemaTablePair.getSchema(), schemaTablePair.getTable(), columns);
    return new SqlgVertex(this, false, true, schemaTablePair.getSchema(), schemaTablePair.getTable(), keyValueMapPair);
}
 
源代码3 项目: alf.io   文件: NotificationManager.java
private static Function<Map<String, String>, byte[]> receiptOrInvoiceFactory(EventRepository eventRepository, Function<Triple<Event, Locale, Map<String, Object>>, Optional<byte[]>> pdfGenerator) {
    return model -> {
        String reservationId = model.get("reservationId");
        Event event = eventRepository.findById(Integer.valueOf(model.get("eventId"), 10));
        Locale language = Json.fromJson(model.get("language"), Locale.class);

        Map<String, Object> reservationEmailModel = Json.fromJson(model.get("reservationEmailModel"), new TypeReference<>() {
        });
        //FIXME hack: reservationEmailModel should be a minimal and typed container
        reservationEmailModel.put("event", event);
        Optional<byte[]> receipt = pdfGenerator.apply(Triple.of(event, language, reservationEmailModel));

        if(receipt.isEmpty()) {
            log.warn("was not able to generate the receipt for reservation id " + reservationId + " for locale " + language);
        }
        return receipt.orElse(null);
    };
}
 
源代码4 项目: dts   文件: ResourceRowLockHelper.java
private static Triple<Long, Long, String> query(final Connection connection, final String tableName,
    final Object rowKey) throws SQLException {
    PreparedStatement pstmt = null;
    try {
        pstmt = connection.prepareStatement(SELECT_SQL);
        pstmt.setString(1, tableName);
        pstmt.setObject(2, rowKey);
        ResultSet resultSet = pstmt.executeQuery();
        Triple<Long, Long, String> triple = null;
        while (resultSet.next()) {
            Long lockedBranchId = resultSet.getLong("branch_id");
            Long lockedTransId = resultSet.getLong("trans_id");
            String lockedInstanceId = resultSet.getString("instance_id");
            triple = new MutableTriple<Long, Long, String>(lockedBranchId, lockedTransId, lockedInstanceId);
        }
        return triple;
    } catch (SQLException e) {
        throw e;
    } finally {
        if (pstmt != null)
            pstmt.close();
    }
}
 
源代码5 项目: arcusplatform   文件: PlaceDAOImpl.java
@Override
public Stream<Triple<UUID, UUID, ServiceLevel>> streamPlaceAndAccountAndServiceLevelByPartitionId(int partitionId) {
  	try(Context ctxt = streamPlaceAndAccountAndServiceLevelByPartitionIdTimer.time()) {
        BoundStatement bs = streamPlaceAndAccountAndServiceLevelByPartitionId.bind(partitionId);
        //bs.setConsistencyLevel(ConsistencyLevel.LOCAL_ONE);
        ResultSet rs = session.execute(bs);
        return stream(rs, (row) -> {
        	ServiceLevel s = ServiceLevel.BASIC;
        	String fromDb = row.getString(PlaceEntityColumns.SERVICE_LEVEL);
        	if(StringUtils.isNotBlank(fromDb)) {
        		s = ServiceLevel.valueOf(fromDb);
        	}
           return new ImmutableTriple<>(row.getUUID(BaseEntityColumns.ID), row.getUUID(PlaceEntityColumns.ACCOUNT_ID), s);
        });
     }
}
 
/**
 * The trie is:
 *     /
 *     0
 *  1*   2*
 */
@Test
public void testGrouping1() {
  UrlTrie trie = new UrlTrie(_property, Arrays.asList(_property + "01", _property + "02"));
  UrlTriePrefixGrouper grouper = new UrlTriePrefixGrouper(trie, 1);
  ArrayList<String> chars = new ArrayList<>();
  ArrayList<FilterOperator> operators = new ArrayList<>();

  while (grouper.hasNext()) {
    Triple<String, FilterOperator, UrlTrieNode> group = grouper.next();
    chars.add(group.getLeft());
    operators.add(group.getMiddle());
  }
  Assert.assertEquals(new String[]{_property + "01", _property + "02"}, chars.toArray());
  Assert.assertEquals(new FilterOperator[]{FilterOperator.CONTAINS, FilterOperator.CONTAINS}, operators.toArray());
}
 
源代码7 项目: Overchan-Android   文件: GalleryInitResult.java
public GalleryInitResult(Parcel parcel) {
    initPosition = parcel.readInt();
    shouldWaitForPageLoaded = parcel.readInt() == 1;
    int n = parcel.readInt();
    attachments = new ArrayList<>(n);
    for (int i=0; i<n; ++i) {
        AttachmentModel attachment = new AttachmentModel();
        attachment.type = parcel.readInt();
        attachment.size = parcel.readInt();
        attachment.thumbnail = parcel.readString();
        attachment.path = parcel.readString();
        attachment.width = parcel.readInt();
        attachment.height = parcel.readInt();
        attachment.originalName = parcel.readString();
        attachment.isSpoiler = parcel.readInt() == 1;
        String hash = parcel.readString();
        String post = parcel.readString();
        attachments.add(Triple.of(attachment, hash, post));
    }
}
 
源代码8 项目: doov   文件: LiveCode.java
private static void modelDiff() {
    FieldModel sample_1 = SampleModels.wrapper();
    FieldModel sample_2 = SampleModels.wrapper();

    sample_1.set(FAVORITE_SITE_NAME_3, null);
    sample_1.set(FAVORITE_SITE_URL_3, null);
    sample_2.set(FAVORITE_SITE_NAME_1, "LesFurets.com");
    sample_2.set(FAVORITE_SITE_URL_1, "www.lesfurets.com");
    sample_2.set(EMAILS_PREFERENCES, Collections.emptyList());

    /* stream all key-values pair from both models */
    Stream.concat(sample_1.stream().map(buildRight), sample_2.stream().map(buildLeft))

                    /* merging key-value pair in a map */
                    .collect(Collectors.toMap(Triple::getMiddle, Function.identity(), merge))

                    /* filter to keep only key with 2 differents values */
                    .values().stream().filter(isNotSame)

                    /* print keys with differents values */
                    .forEach(System.out::println);
}
 
@Test
void processPendingTickets() {

    when(configurationManager.getFor(eq(Set.of(ENABLE_WAITING_QUEUE, ENABLE_PRE_REGISTRATION)), any()))
        .thenReturn(Map.of(
            ENABLE_WAITING_QUEUE, new ConfigurationManager.MaybeConfiguration(ENABLE_WAITING_QUEUE, new ConfigurationKeyValuePathLevel( "", "true", null)),
            ENABLE_PRE_REGISTRATION, new ConfigurationManager.MaybeConfiguration(ENABLE_PRE_REGISTRATION)
        ));

    when(messageSource.getMessage(anyString(), any(), eq(Locale.ENGLISH))).thenReturn("subject");
    when(subscription.getLocale()).thenReturn(Locale.ENGLISH);
    when(subscription.getEmailAddress()).thenReturn("me");
    ZonedDateTime expiration = ZonedDateTime.now().plusDays(1);
    when(waitingQueueManager.distributeSeats(eq(event))).thenReturn(Stream.of(Triple.of(subscription, reservation, expiration)));
    String reservationId = "reservation-id";
    when(ticketReservationManager.createTicketReservation(eq(event), anyList(), anyList(), any(Date.class), eq(Optional.empty()), any(Locale.class), eq(true))).thenReturn(reservationId);
    processor.handleWaitingTickets();
    verify(ticketReservationManager).createTicketReservation(eq(event), eq(Collections.singletonList(reservation)), anyList(), eq(Date.from(expiration.toInstant())), eq(Optional.empty()), eq(Locale.ENGLISH), eq(true));
    verify(notificationManager).sendSimpleEmail(eq(event), eq(reservationId), eq("me"), eq("subject"), any(TemplateGenerator.class));
}
 
@Test
public void testConfigureRegexRegions() throws Exception {
  XMLConfiguration conf = new XMLConfiguration(getResource(this.getClass(), "regexRegions.xml"));

  bolt.configureRegexRegions(conf);

  assertThat(bolt.groupSearchReplaceList.size(), is(2));

  Triple<Pattern, String, String> entry0 = bolt.groupSearchReplaceList.get(0);
  Triple<Pattern, String, String> entry1 = bolt.groupSearchReplaceList.get(1);

  assertNotNull(entry0.getLeft());
  assertThat(entry0.getMiddle(), is("regex0"));
  assertThat(entry0.getRight(), is("replacement0"));
  assertNotNull(entry1.getLeft());
  assertThat(entry1.getMiddle(), is("regex1"));
  assertThat(entry1.getRight(), is("replacement1"));
}
 
源代码11 项目: twister2   文件: FSSorter.java
public Object next() {
  HeapNode min = heap.extractMin();

  int list = min.listNo;
  FilePart p = openList.get(list);
  List<Tuple> keyValues = p.keyValues.getLeft();

  if (keyValues.size() <= p.currentIndex) {
    String fileName = folder + "/part_" + list;
    // we need to load the next file, we don't need to do anything for in-memory
    // also if the file reached end, we don't need to do anything
    if (list < noOfFiles && p.keyValues.getMiddle() < p.keyValues.getRight()) {
      Triple<List<Tuple>, Long, Long> values = FileLoader.openFilePart(fileName,
          p.keyValues.getMiddle(), openBytes, keyType, dataType, deserializer);
      // set the new values to the list
      p.keyValues = values;
    }
  }

  return min.data;
}
 
源代码12 项目: alf.io   文件: WaitingQueueManagerTest.java
@Test
void processPreReservations() {
    Ticket ticket = mock(Ticket.class);
    WaitingQueueSubscription subscription = mock(WaitingQueueSubscription.class);
    when(subscription.isPreSales()).thenReturn(true);
    when(eventRepository.countExistingTickets(eq(eventId))).thenReturn(10);
    when(event.getZoneId()).thenReturn(ZoneId.systemDefault());
    when(waitingQueueRepository.countWaitingPeople(eq(eventId))).thenReturn(1);
    when(ticketRepository.countWaiting(eq(eventId))).thenReturn(0);
    when(configurationManager.getFor(eq(ENABLE_PRE_REGISTRATION), any())).thenReturn(new ConfigurationManager.MaybeConfiguration(ENABLE_PRE_REGISTRATION, new ConfigurationKeyValuePathLevel(null, "true", null)));
    when(configurationManager.getFor(eq(WAITING_QUEUE_RESERVATION_TIMEOUT), any())).thenReturn(new ConfigurationManager.MaybeConfiguration(WAITING_QUEUE_RESERVATION_TIMEOUT));
    when(ticketRepository.selectWaitingTicketsForUpdate(eventId, Ticket.TicketStatus.PRE_RESERVED.name(), 1)).thenReturn(Collections.singletonList(ticket));
    when(waitingQueueRepository.loadAllWaitingForUpdate(eventId)).thenReturn(Collections.singletonList(subscription));
    when(waitingQueueRepository.loadWaiting(eventId, 1)).thenReturn(Collections.singletonList(subscription));
    Stream<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime>> stream = manager.distributeSeats(event);
    assertEquals(1L, stream.count());
    verify(waitingQueueRepository).loadAllWaitingForUpdate(eq(eventId));
    verify(waitingQueueRepository).loadWaiting(eq(eventId), eq(1));
    verify(ticketRepository).countWaiting(eq(eventId));
    verify(ticketRepository, never()).revertToFree(eq(eventId));
    verify(ticketRepository).countPreReservedTickets(eq(eventId));
    verify(ticketRepository).preReserveTicket(anyList());
    verify(ticketRepository).selectWaitingTicketsForUpdate(eq(eventId), anyString(), anyInt());
}
 
源代码13 项目: azure-keyvault-java   文件: RsaKeyTest.java
@Test
public void testRsa15() throws Exception {

    RsaKey key = getTestRsaKey();

    // Wrap and Unwrap
    Pair<byte[], String> wrapped   = key.wrapKeyAsync(CEK, Rsa15.ALGORITHM_NAME).get();
    byte[]               unwrapped = key.unwrapKeyAsync(wrapped.getLeft(), wrapped.getRight()).get();

    // Assert
    assertEquals(Rsa15.ALGORITHM_NAME, wrapped.getRight());
    assertArrayEquals(CEK, unwrapped);

    // Encrypt and Decrypt
    Triple<byte[], byte[], String> encrypted = key.encryptAsync(CEK, null, null, Rsa15.ALGORITHM_NAME).get();
    byte[]                         decrypted = key.decryptAsync(encrypted.getLeft(), null, null, null, encrypted.getRight()).get();

    // Assert
    assertEquals(Rsa15.ALGORITHM_NAME, encrypted.getRight());
    assertArrayEquals(CEK, decrypted);

    key.close();
}
 
源代码14 项目: sqlg   文件: BaseSqlDialect.java
@Override
public List<Triple<String, String, String>> getVertexTables(DatabaseMetaData metaData) {
    List<Triple<String, String, String>> vertexTables = new ArrayList<>();
    String[] types = new String[]{"TABLE"};
    try {
        //load the vertices
        try (ResultSet vertexRs = metaData.getTables(null, null, Topology.VERTEX_PREFIX + "%", types)) {
            while (vertexRs.next()) {
                String tblCat = vertexRs.getString(1);
                String schema = vertexRs.getString(2);
                String table = vertexRs.getString(3);

                //verify the table name matches our pattern
                if (!table.startsWith(Topology.VERTEX_PREFIX)) {
                    continue;
                }
                vertexTables.add(Triple.of(tblCat, schema, table));
            }
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    return vertexTables;
}
 
@Test
public void testDistributeSeatsFirstCategoryIsUnbounded() throws Exception {
    List<TicketCategoryModification> categories = getPreSalesTicketCategoryModifications(false, AVAILABLE_SEATS, true, 10);
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager, eventRepository);
    Event event = pair.getKey();
    TicketCategory firstCategory = eventManager.loadTicketCategories(event).stream().filter(t->t.getName().equals("defaultFirst")).findFirst().orElseThrow(IllegalStateException::new);
    configurationManager.saveCategoryConfiguration(firstCategory.getId(), event.getId(), Collections.singletonList(new ConfigurationModification(null, ConfigurationKeys.MAX_AMOUNT_OF_TICKETS_BY_RESERVATION.getValue(), "1")), pair.getRight()+"_owner");
    configurationManager.saveSystemConfiguration(ConfigurationKeys.ENABLE_PRE_REGISTRATION, "true");
    configurationManager.saveSystemConfiguration(ConfigurationKeys.ENABLE_WAITING_QUEUE, "true");
    boolean result = waitingQueueManager.subscribe(event, customerJohnDoe(event), "[email protected]", null, Locale.ENGLISH);
    assertTrue(result);
    List<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime>> subscriptions = waitingQueueManager.distributeSeats(event).collect(Collectors.toList());
    assertEquals(1, subscriptions.size());
    Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime> subscriptionDetail = subscriptions.get(0);
    assertEquals("[email protected]", subscriptionDetail.getLeft().getEmailAddress());
    TicketReservationWithOptionalCodeModification reservation = subscriptionDetail.getMiddle();
    assertEquals(Integer.valueOf(firstCategory.getId()), reservation.getTicketCategoryId());
    assertEquals(Integer.valueOf(1), reservation.getAmount());
    assertTrue(subscriptionDetail.getRight().isAfter(ZonedDateTime.now()));

}
 
源代码16 项目: alf.io   文件: AdminReservationRequestManager.java
private Result<Triple<TicketReservation, List<Ticket>, Event>> processReservation(AdminReservationRequest request, Event event, User user) {
    DefaultTransactionDefinition definition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_NESTED);
    TransactionTemplate template = new TransactionTemplate(transactionManager, definition);
    return template.execute(status -> {
        var savepoint = status.createSavepoint();
        try {
            String eventName = event.getShortName();
            String username = user.getUsername();
            Result<Triple<TicketReservation, List<Ticket>, Event>> result = adminReservationManager.createReservation(request.getBody(), eventName, username)
                .flatMap(r -> adminReservationManager.confirmReservation(eventName, r.getLeft().getId(), username, orEmpty(request.getBody().getNotification())));
            if(!result.isSuccess()) {
                status.rollbackToSavepoint(savepoint);
            }
            return result;
        } catch(Exception ex) {
            status.rollbackToSavepoint(savepoint);
            return Result.error(singletonList(ErrorCode.custom("", ex.getMessage())));
        }
    });
}
 
源代码17 项目: yauaa   文件: RunBenchmarks.java
@Test
public void runBenchmarks() {

    uaa = UserAgentAnalyzer
        .newBuilder()
        .withoutCache()
        .preheat(10000)
        .build();

    List<Triple<Counter, String, String>> testCases = createTestCasesList();

    System.gc(); // Avoid gc during tests

    for (int run = 1; run < 10000; run++) {
        if (run % 100 == 0) {
            System.gc(); // Avoid gc during tests
            LOG.info("Did {} runs", run);
        }
        testCases.forEach(this::doTest);
    }

    testCases.forEach(this::printResults);

}
 
源代码18 项目: incubator-gobblin   文件: UrlTriePrefixGrouper.java
@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;
}
 
源代码19 项目: sqlg   文件: MariadbDialect.java
@Override
public List<Triple<String, String, String>> getVertexTables(DatabaseMetaData metaData) {
    List<Triple<String, String, String>> vertexTables = new ArrayList<>();
    String[] types = new String[]{"TABLE"};
    try {
        //load the vertices
        try (ResultSet vertexRs = metaData.getTables(null, null, "V_%", types)) {
            while (vertexRs.next()) {
                //MariaDb does not support schemas.
                String tblCat = null;
                String schema = vertexRs.getString(1);
                String table = vertexRs.getString(3);

                //verify the table name matches our pattern
                if (!table.startsWith("V_")) {
                    continue;
                }
                vertexTables.add(Triple.of(tblCat, schema, table));
            }
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    return vertexTables;
}
 
源代码20 项目: clust4j   文件: NNHSTests.java
@Test
public void testBall1() {
	final Array2DRowRealMatrix mat = new Array2DRowRealMatrix(a, false);
	BallTree ball = new BallTree(mat);
	
	QuadTup<double[][], int[], NodeData[], double[][][]> arrays = ball.getArrays();
	
	assertTrue(MatUtils.equalsExactly(arrays.getFirst(), a));
	assertTrue(VecUtils.equalsExactly(new int[]{0,1,2}, arrays.getSecond()));
	
	Triple<Integer, Integer, Integer> stats = ball.getTreeStats();
	assertTrue(stats.getLeft() == 0);
	assertTrue(stats.getMiddle() == 0);
	assertTrue(stats.getRight() ==0);
	
	NodeData data = arrays.getThird()[0];
	assertTrue(data.idx_start == 0);
	assertTrue(data.idx_end == 3);
	assertTrue(data.is_leaf);
	assertTrue(data.radius == 6.716480559869961);
	
	double[][][] trip = arrays.getFourth();
	assertTrue(trip.length == 1);
	assertTrue(trip[0][0][0] == 1.6666666666666667);
	assertTrue(trip[0][0][1] == 2.3333333333333333);
	assertTrue(trip[0][0][2] == 2.6666666666666667);
	assertTrue(trip[0][0][3] == 2.6666666666666667);
}
 
源代码21 项目: Survivalist   文件: ItemBreakingTracker.java
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);
    }
}
 
源代码22 项目: youran   文件: FreeMarkerConfigFactory.java
/**
 * 同步加锁构建freemarker配置,并放入缓存
 *
 * @param templatePO
 * @return
 */
private synchronized Triple<Configuration, Integer, String> buildAndCache(CodeTemplatePO templatePO) {
    Integer templateId = templatePO.getTemplateId();
    Triple<Configuration, Integer, String> triple = cache.get(templateId);
    if (triple == null || !Objects.equals(triple.getMiddle(), templatePO.getInnerVersion())) {
        triple = this.buildTriple(templatePO);
        cache.put(templateId, triple);
    }
    return triple;
}
 
@Test
public void testGroupToPagesWithContainsOperator() {
  List<String> pages = Arrays.asList(_property + "13", _property + "14");
  UrlTrie trie = new UrlTrie(_property, pages);
  ArrayList<String> actual =
      UrlTriePrefixGrouper.groupToPages(Triple.of(_property, FilterOperator.CONTAINS, trie.getRoot()));
  Assert.assertEquals(actual.toArray(), pages.toArray());
}
 
源代码24 项目: alf.io   文件: WaitingQueueManager.java
private Stream<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime>> distributeAvailableSeats(Event event, Ticket.TicketStatus status, IntSupplier availableSeatSupplier) {
    int availableSeats = availableSeatSupplier.getAsInt();
    int eventId = event.getId();
    log.debug("processing {} subscribers from waiting list", availableSeats);
    List<TicketCategory> unboundedCategories = ticketCategoryRepository.findUnboundedOrderByExpirationDesc(eventId);
    Iterator<Ticket> tickets = ticketRepository.selectWaitingTicketsForUpdate(eventId, status.name(), availableSeats)
        .stream()
        .filter(t -> t.getCategoryId() != null || !unboundedCategories.isEmpty())
        .iterator();
    int expirationTimeout = configurationManager.getFor(WAITING_QUEUE_RESERVATION_TIMEOUT, ConfigurationLevel.event(event)).getValueAsIntOrDefault(4);
    ZonedDateTime expiration = ZonedDateTime.now(event.getZoneId()).plusHours(expirationTimeout).with(WorkingDaysAdjusters.defaultWorkingDays());

    if(!tickets.hasNext()) {
        log.warn("Unable to assign tickets, returning an empty stream");
        return Stream.empty();
    }
    return waitingQueueRepository.loadWaiting(eventId, availableSeats).stream()
        .map(wq -> Pair.of(wq, tickets.next()))
        .map(pair -> {
            TicketReservationModification ticketReservation = new TicketReservationModification();
            ticketReservation.setAmount(1);
            Integer categoryId = Optional.ofNullable(pair.getValue().getCategoryId()).orElseGet(() -> findBestCategory(unboundedCategories, pair.getKey()).orElseThrow(RuntimeException::new).getId());
            ticketReservation.setTicketCategoryId(categoryId);
            return Pair.of(pair.getLeft(), new TicketReservationWithOptionalCodeModification(ticketReservation, Optional.empty()));
        })
        .map(pair -> Triple.of(pair.getKey(), pair.getValue(), expiration));
}
 
源代码25 项目: sqlg   文件: MysqlDialect.java
@Override
public PropertyType sqlArrayTypeNameToPropertyType(String typeName, SqlgGraph sqlgGraph, String schema, String table, String columnName, ListIterator<Triple<String, Integer, String>> metaDataIter) {
    switch (typeName) {
        case "BOOLEAN ARRAY":
            return PropertyType.BOOLEAN_ARRAY;
        case "SMALLINT ARRAY":
            return PropertyType.SHORT_ARRAY;
        case "INTEGER ARRAY":
            return PropertyType.INTEGER_ARRAY;
        case "BIGINT ARRAY":
            return PropertyType.LONG_ARRAY;
        case "DOUBLE ARRAY":
            return PropertyType.DOUBLE_ARRAY;
        case "DATE ARRAY":
            return PropertyType.LOCALDATE_ARRAY;
        case "TIME WITH TIME ZONE ARRAY":
            return PropertyType.LOCALTIME_ARRAY;
        case "TIMESTAMP WITH TIME ZONE ARRAY":
            //need to check the next column to know if its a LocalDateTime or ZonedDateTime array
            Triple<String, Integer, String> metaData = metaDataIter.next();
            metaDataIter.previous();
            if (metaData.getLeft().startsWith(columnName + "~~~")) {
                return PropertyType.ZONEDDATETIME_ARRAY;
            } else {
                return PropertyType.LOCALDATETIME_ARRAY;
            }
        default:
            if (typeName.contains("VARCHAR") && typeName.contains("ARRAY")) {
                return PropertyType.STRING_ARRAY;
            } else {
                throw new RuntimeException(String.format("Array type not supported typeName = %s", typeName));
            }
    }
}
 
源代码26 项目: aion   文件: AionBlockchainImpl.java
/**
 * 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();
    }
}
 
源代码27 项目: aion   文件: StandaloneBlockchain.java
/** Required by contracts that are not precompiled to get the correct VM type during use. */
public Builder withContractIndex(
        AionAddress contract,
        ByteArrayWrapper codeHash,
        ByteArrayWrapper inceptionBlock,
        InternalVmType vmType) {
    this.contractIndex.put(contract, Triple.of(codeHash, inceptionBlock, vmType));
    return this;
}
 
源代码28 项目: Overchan-Android   文件: TabsTrackerService.java
private static int findTab(List<Triple<String, String, String>> list, String tabUrl, String tabTitle) {
    for (int i=0; i<list.size(); ++i) {
        Triple<String, String, String> triple = list.get(i);
        if (tabUrl == null) {
            if (triple.getLeft() == null && tabTitle.equals(triple.getRight())) {
                return i;
            }
        } else {
            if (tabUrl.equals(triple.getLeft())) {
                return i;
            }
        }
    }
    return -1;
}
 
源代码29 项目: sqlg   文件: H2Dialect.java
@Override
public PropertyType sqlTypeToPropertyType(SqlgGraph sqlgGraph, String schema, String table, String column,
                                          int sqlType, String typeName, ListIterator<Triple<String, Integer, String>> metaDataIter) {
    switch (sqlType) {
        case Types.BOOLEAN:
            return PropertyType.BOOLEAN;
        case Types.SMALLINT:
            return PropertyType.SHORT;
        case Types.INTEGER:
            return PropertyType.INTEGER;
        case Types.BIGINT:
            return PropertyType.LONG;
        case Types.REAL:
            return PropertyType.FLOAT;
        case Types.DOUBLE:
            return PropertyType.DOUBLE;
        case Types.VARCHAR:
            return PropertyType.STRING;
        case Types.TIMESTAMP:
            return PropertyType.LOCALDATETIME;
        case Types.DATE:
            return PropertyType.LOCALDATE;
        case Types.TIME:
            return PropertyType.LOCALTIME;
        case Types.VARBINARY:
            return PropertyType.BYTE_ARRAY;
        case Types.ARRAY:
            return sqlArrayTypeNameToPropertyType(typeName, sqlgGraph, schema, table, column, metaDataIter);
        default:
            throw new IllegalStateException("Unknown sqlType " + sqlType);
    }
}
 
源代码30 项目: cineast   文件: CaptionTextImporter.java
/**
 * @return Pair mapping a segmentID to a List of Descriptions
 */
@Override
public Triple<String, String, String> readNext() {
  try {
    Optional<Triple<String, String, String>> node = nextPair();
    if (!node.isPresent()) {
      return null;
    }
    return node.get();
  } catch (NoSuchElementException e) {
    return null;
  }
}
 
 类所在包
 同包方法