Example usage for org.apache.commons.lang3.tuple Pair getKey

List of usage examples for org.apache.commons.lang3.tuple Pair getKey

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getKey.

Prototype

@Override
public final L getKey() 

Source Link

Document

Gets the key from this pair.

This method implements the Map.Entry interface returning the left element as the key.

Usage

From source file:alfio.manager.TicketReservationManagerIntegrationTest.java

@Test
public void testTicketSelection() {
    List<TicketCategoryModification> categories = Arrays.asList(
            new TicketCategoryModification(null, "default", AVAILABLE_SEATS,
                    new DateTimeModification(LocalDate.now(), LocalTime.now()),
                    new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN,
                    false, "", false, null, null, null, null, null),
            new TicketCategoryModification(null, "default", 10,
                    new DateTimeModification(LocalDate.now(), LocalTime.now()),
                    new DateTimeModification(LocalDate.now(), LocalTime.now()), DESCRIPTION, BigDecimal.TEN,
                    false, "", true, null, null, null, null, null));
    Pair<Event, String> eventAndUsername = initEvent(categories, organizationRepository, userManager,
            eventManager, eventRepository);
    Event event = eventAndUsername.getKey();

    TicketCategory bounded = ticketCategoryRepository.findByEventId(event.getId()).stream()
            .filter(TicketCategory::isBounded).findFirst().orElseThrow(IllegalStateException::new);
    TicketCategory unbounded = ticketCategoryRepository.findByEventId(event.getId()).stream()
            .filter(t -> !t.isBounded()).findFirst().orElseThrow(IllegalStateException::new);

    assertEquals(0, eventStatisticsManager.loadModifiedTickets(event.getId(), bounded.getId(), 0, null).size());
    assertEquals(Integer.valueOf(0),
            eventStatisticsManager.countModifiedTicket(event.getId(), bounded.getId(), null));
    assertEquals(0,//from www.ja  va  2 s .c om
            eventStatisticsManager.loadModifiedTickets(event.getId(), unbounded.getId(), 0, null).size());

    TicketReservationModification tr = new TicketReservationModification();
    tr.setAmount(10);
    tr.setTicketCategoryId(bounded.getId());

    TicketReservationModification tr2 = new TicketReservationModification();
    tr2.setAmount(9);
    tr2.setTicketCategoryId(unbounded.getId());

    TicketReservationWithOptionalCodeModification mod = new TicketReservationWithOptionalCodeModification(tr,
            Optional.empty());
    TicketReservationWithOptionalCodeModification mod2 = new TicketReservationWithOptionalCodeModification(tr2,
            Optional.empty());
    String reservationId = ticketReservationManager.createTicketReservation(event, Arrays.asList(mod, mod2),
            Collections.emptyList(), DateUtils.addDays(new Date(), 1), Optional.empty(), Optional.empty(),
            Locale.ENGLISH, false);

    List<TicketReservation> reservations = ticketReservationManager
            .findAllReservationsInEvent(event.getId(), 0, null, null).getKey();
    assertTrue(reservations.size() == 1);
    assertEquals(reservationId, reservations.get(0).getId());

    List<Ticket> pendingTickets = ticketRepository
            .findPendingTicketsInCategories(Arrays.asList(bounded.getId(), unbounded.getId()));
    assertEquals(19, pendingTickets.size());
    pendingTickets.forEach(t -> assertEquals(1000, t.getFinalPriceCts()));
    List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
    assertEquals(1, tickets.size());
    assertTrue(tickets.stream().allMatch(t -> t.getCategoryId() == null));

    TotalPrice totalPrice = ticketReservationManager.totalReservationCostWithVAT(reservationId);

    assertEquals(0, ticketReservationManager.getPendingPayments(event).size());

    PaymentResult confirm = ticketReservationManager.confirm(null, null, event, reservationId,
            "email@example.com", new CustomerName("full name", "full", "name", event), Locale.ENGLISH,
            "billing address", totalPrice, Optional.empty(), Optional.of(PaymentProxy.OFFLINE), false, null,
            null, null);

    assertTrue(confirm.isSuccessful());

    assertEquals(TicketReservation.TicketReservationStatus.OFFLINE_PAYMENT,
            ticketReservationManager.findById(reservationId).get().getStatus());

    assertEquals(1, ticketReservationManager.getPendingPayments(event).size());

    Date now = new Date();
    Date from = DateUtils.addDays(now, -1);
    Date to = DateUtils.addDays(now, 1);

    assertTrue(ticketReservationRepository.getSoldStatistic(event.getId(), from, to).isEmpty()); // -> no reservations
    ticketReservationManager.validateAndConfirmOfflinePayment(reservationId, event, new BigDecimal("190.00"),
            eventAndUsername.getValue());

    assertEquals(19,
            ticketReservationRepository.getSoldStatistic(event.getId(), from, to).get(0).getTicketSoldCount()); // -> 19 tickets reserved

    assertEquals(10,
            eventStatisticsManager.loadModifiedTickets(event.getId(), bounded.getId(), 0, null).size());
    assertEquals(Integer.valueOf(10),
            eventStatisticsManager.countModifiedTicket(event.getId(), bounded.getId(), null));
    assertEquals(9,
            eventStatisticsManager.loadModifiedTickets(event.getId(), unbounded.getId(), 0, null).size());
    assertEquals(Integer.valueOf(9),
            eventStatisticsManager.countModifiedTicket(event.getId(), unbounded.getId(), null));

    assertEquals(TicketReservation.TicketReservationStatus.COMPLETE,
            ticketReservationManager.findById(reservationId).get().getStatus());

    //-------------------

    TicketReservationModification trForDelete = new TicketReservationModification();
    trForDelete.setAmount(1);
    trForDelete.setTicketCategoryId(unbounded.getId());
    TicketReservationWithOptionalCodeModification modForDelete = new TicketReservationWithOptionalCodeModification(
            trForDelete, Optional.empty());
    String reservationId2 = ticketReservationManager.createTicketReservation(event,
            Collections.singletonList(modForDelete), Collections.emptyList(), DateUtils.addDays(new Date(), 1),
            Optional.empty(), Optional.empty(), Locale.ENGLISH, false);

    ticketReservationManager.confirm(null, null, event, reservationId2, "email@example.com",
            new CustomerName("full name", "full", "name", event), Locale.ENGLISH, "billing address", totalPrice,
            Optional.empty(), Optional.of(PaymentProxy.OFFLINE), false, null, null, null);

    assertTrue(ticketReservationManager.findById(reservationId2).isPresent());

    ticketReservationManager.deleteOfflinePayment(event, reservationId2, false);

    Assert.assertFalse(ticketReservationManager.findById(reservationId2).isPresent());
}

From source file:com.cisco.oss.foundation.http.AbstractHttpClient.java

private List<InternalServerProxy> updateServerListBasedOnConfig(final List<InternalServerProxy> serversList,
        final InternalServerProxyMetadata metadata) {

    // iterate host and port pairs and create ad new servers to the server
    // list.//from   w ww .  ja v  a  2 s. c  o m
    for (Pair<String, Integer> hostPort : metadata.getHostAndPortPairs()) {

        final String hostEntry = hostPort.getKey();
        final int portEntry = hostPort.getValue();

        final InternalServerProxy internalServerProxy = createInternalServerProxy(metadata, hostEntry,
                portEntry);
        serversList.add(internalServerProxy);
    }

    return serversList;
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdController.java

private byte[] createRequestXml(String action, ImmutablePair<String, String>... params) {
    try {//from ww w. j av  a  2 s.co  m
        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage soapMessage = factory.createMessage();

        SOAPBodyElement actionElement = soapMessage.getSOAPBody().addBodyElement(new QName(null, action, "m"));
        actionElement.addNamespaceDeclaration("m", serviceType);

        for (Pair<String, String> param : params) {
            SOAPElement paramElement = actionElement.addChildElement(QName.valueOf(param.getKey()));
            paramElement.setValue(param.getValue());
        }

        soapMessage.getSOAPPart().setXmlStandalone(true);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(new DOMSource(soapMessage.getSOAPPart()), new StreamResult(baos));

        return baos.toByteArray();
    } catch (IllegalArgumentException | SOAPException | TransformerException | DOMException e) {
        throw new IllegalStateException(e); // should never happen
    }
}

From source file:com.nextdoor.bender.operation.substitution.regex.RegexSubstitution.java

@Override
protected void doSubstitution(InternalEvent ievent, DeserializedEvent devent, Map<String, Object> nested) {
    Pair<String, Map<String, Object>> kv;
    try {/*from  w w w.  ja v  a2  s .  c  o m*/
        kv = getRegexMatches(devent);
    } catch (FieldNotFoundException e) {
        if (this.failSrcNotFound) {
            throw new OperationException(e);
        }
        return;
    }

    nested.putAll(kv.getValue());

    /*
     * Remove source field
     */
    if (this.removeSrcField) {
        try {
            devent.removeField(kv.getKey());
        } catch (FieldNotFoundException e) {
            if (this.failSrcNotFound) {
                throw new OperationException(e);
            }
        }
    }
}

From source file:alfio.manager.WaitingQueueManagerIntegrationTest.java

@Test
public void testSubscribeDenied() {
    List<TicketCategoryModification> categories = getPreSalesTicketCategoryModifications(false, AVAILABLE_SEATS,
            true, 10);//ww w  .j ava  2s  . c  o m
    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");
    configurationRepository.insertEventLevel(event.getOrganizationId(), event.getId(),
            ConfigurationKeys.STOP_WAITING_QUEUE_SUBSCRIPTIONS.name(), "true", "");
    //subscription should now be denied
    boolean result = waitingQueueManager.subscribe(event, customerJohnDoe(event), "john@doe.com", null,
            Locale.ENGLISH);
    assertFalse(result);
}

From source file:alfio.manager.WaitingQueueManagerIntegrationTest.java

@Test
public void testDistributeSeatsFirstCategoryIsBounded() throws Exception {
    List<TicketCategoryModification> categories = getPreSalesTicketCategoryModifications(true, 10, true, 10);
    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);//www.j  ava2s  .co  m
    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), "john@doe.com", 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("john@doe.com", 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()));

}

From source file:alfio.manager.WaitingQueueManagerIntegrationTest.java

@Test
public void testDistributeSeatsFirstCategoryIsUnbounded() throws Exception {
    List<TicketCategoryModification> categories = getPreSalesTicketCategoryModifications(false, AVAILABLE_SEATS,
            true, 10);// w  ww .ja  v  a  2  s  . c o  m
    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), "john@doe.com", 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("john@doe.com", 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()));

}

From source file:com.spotify.heroic.cluster.CoreClusterManager.java

@Override
public List<ClusterShard> useOptionalGroup(final Optional<String> group) {
    final ImmutableList.Builder<ClusterShard> shards = ImmutableList.builder();

    for (final Pair<Map<String, String>, List<ClusterNode>> e : findFromAllShards()) {
        shards.add(new ClusterShard(async, e.getKey(),
                ImmutableList.copyOf(e.getValue().stream().map(c -> c.useOptionalGroup(group)).iterator())));
    }//ww w  . jav  a 2s .  com

    return shards.build();
}

From source file:com.hortonworks.streamline.streams.notification.service.NotificationQueueHandler.java

/**
 * Attempt re-delivery of a previously enqueued notification.
 *
 * @param notificationId id of a previously submitted notification.
 *///from   w ww . j  av a2s . c o  m
public void resubmit(String notificationId) {
    Pair<NotificationQueueTask, Future<?>> taskStatus = taskMap.get(notificationId);
    if (taskStatus == null) {
        throw new NotificationServiceException(
                "Could not find a previously enqueued task" + " for notification id " + notificationId);
    } else if (!taskStatus.getValue().isDone()) {
        throw new NotificationServiceException(
                "Previously enqueued task" + " for notification id " + notificationId + " is not done");

    }
    Future<?> future = executorService.submit(taskStatus.getKey());
    taskMap.put(notificationId, Pair.of(taskStatus.getKey(), future));
}

From source file:massbank.Record.java

public String toString() {
    StringBuilder sb = new StringBuilder();

    sb.append("ACCESSION: " + ACCESSION() + "\n");
    sb.append("RECORD_TITLE: " + RECORD_TITLE() + "\n");
    sb.append("DATE: " + DATE() + "\n");
    sb.append("AUTHORS: " + AUTHORS() + "\n");
    sb.append("LICENSE: " + LICENSE() + "\n");
    if (COPYRIGHT() != null)
        sb.append("COPYRIGHT: " + COPYRIGHT() + "\n");
    if (PUBLICATION() != null)
        sb.append("PUBLICATION: " + PUBLICATION() + "\n");
    if (COMMENT() != null) {
        for (String comment : COMMENT())
            sb.append("COMMENT: " + comment + "\n");
    }/*from www  .j  a  va 2  s  .  c o  m*/
    if (CH_NAME() != null) {
        for (String ch_name : CH_NAME())
            sb.append("CH$NAME: " + ch_name + "\n");
    }
    sb.append("CH$COMPOUND_CLASS: " + CH_COMPOUND_CLASS() + "\n");
    sb.append("CH$FORMULA: " + CH_FORMULA() + "\n");
    sb.append("CH$EXACT_MASS: " + CH_EXACT_MASS() + "\n");
    try {
        sb.append("CH$SMILES: " + CH_SMILES() + "\n");
    } catch (CDKException e) {
        System.err.println(e.getMessage());
        sb.append("CH$SMILES: null\n");
    }
    try {
        sb.append("CH$IUPAC: " + CH_IUPAC() + "\n");
    } catch (CDKException e) {
        System.err.println(e.getMessage());
        sb.append("CH$IUPAC: null\n");
    }
    if (CH_LINK() != null) {
        for (Pair<String, String> link : CH_LINK())
            sb.append("CH$LINK: " + link.getKey() + " " + link.getValue() + "\n");
    }
    if (SP_SCIENTIFIC_NAME() != null)
        sb.append("SP$SCIENTIFIC_NAME: " + SP_SCIENTIFIC_NAME() + "\n");
    if (SP_LINEAGE() != null)
        sb.append("SP$LINEAGE: " + SP_LINEAGE() + "\n");
    if (SP_LINK() != null) {
        for (Pair<String, String> link : SP_LINK())
            sb.append("SP$LINK: " + link.getKey() + " " + link.getValue() + "\n");
    }
    if (SP_SAMPLE() != null) {
        for (String sample : SP_SAMPLE())
            sb.append("SP$SAMPLE: " + sample + "\n");
    }
    sb.append("AC$INSTRUMENT: " + AC_INSTRUMENT() + "\n");
    sb.append("AC$INSTRUMENT_TYPE: " + AC_INSTRUMENT_TYPE().toString() + "\n");
    sb.append("AC$MASS_SPECTROMETRY: MS_TYPE: " + AC_MASS_SPECTROMETRY_MS_TYPE() + "\n");
    sb.append("AC$MASS_SPECTROMETRY: ION_MODE: " + AC_MASS_SPECTROMETRY_ION_MODE() + "\n");
    if (AC_MASS_SPECTROMETRY() != null) {
        for (Pair<String, String> ac_mass_spectrometry : AC_MASS_SPECTROMETRY())
            sb.append("AC$MASS_SPECTROMETRY: " + ac_mass_spectrometry.getKey() + " "
                    + ac_mass_spectrometry.getValue() + "\n");
    }
    if (AC_CHROMATOGRAPHY() != null) {
        for (Pair<String, String> ac_chromatography : AC_CHROMATOGRAPHY())
            sb.append("AC$CHROMATOGRAPHY: " + ac_chromatography.getKey() + " " + ac_chromatography.getValue()
                    + "\n");
    }
    if (MS_FOCUSED_ION() != null) {
        for (Pair<String, String> ms_focued_ion : MS_FOCUSED_ION())
            sb.append("MS$FOCUSED_ION: " + ms_focued_ion.getKey() + " " + ms_focued_ion.getValue() + "\n");
    }
    if (MS_DATA_PROCESSING() != null) {
        for (Pair<String, String> ms_data_processing : MS_DATA_PROCESSING())
            sb.append("MS$DATA_PROCESSING: " + ms_data_processing.getKey() + " " + ms_data_processing.getValue()
                    + "\n");
    }
    sb.append("PK$SPLASH: " + PK_SPLASH() + "\n");

    if (PK_ANNOTATION_HEADER() != null) {
        sb.append("PK$ANNOTATION:");
        for (String annotation_header_item : PK_ANNOTATION_HEADER())
            sb.append(" " + annotation_header_item);
        sb.append("\n");
        for (List<String> annotation_line : PK_ANNOTATION()) {
            sb.append(" ");
            for (String annotation_item : annotation_line)
                sb.append(" " + annotation_item);
            sb.append("\n");
        }
    }

    sb.append("PK$NUM_PEAK: " + PK_NUM_PEAK() + "\n");
    sb.append("PK$PEAK: m/z int. rel.int.\n");
    for (List<Double> peak_line : PK_PEAK()) {
        sb.append(" ");
        for (Double peak_line_item : peak_line)
            sb.append(" " + peak_line_item.toString());
        sb.append("\n");
    }

    /*
     * // PK$ANNOTATION: m/z tentative_formula formula_count mass error(ppm) //
     * 57.0701 C4H9+ 1 57.0699 4.61 // 67.0542 C5H7+ 1 67.0542 0.35 // 69.0336
     * C4H5O+ 1 69.0335 1.14 sb.append("PK$NUM_PEAK: " + this.PK$PEAK_MZ.length +
     * "\n"); sb.append("PK$PEAK: m/z int. rel.int." + "\n"); for(int idx = 0; idx <
     * this.PK$PEAK_MZ.length; idx++) sb.append("  " + this.PK$PEAK_MZ[idx] + " " +
     * this.PK$PEAK_INT[idx] + " " + this.PK$PEAK_REL[idx] + "\n");
     */
    sb.append("//");

    return sb.toString();
}