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:net.lyonlancer5.mcmp.unmapi.xejon.XejonLoader.java

public void load() {
    for (Pair<String, Pair<File, JsonElement>> jsonPack : jsonPackIds) {
        LOGGER.info("Loading JSON pack: " + jsonPack.getKey());
        try {//from   w  w w . j  av  a 2  s  .  c  o m
            mURLClassLoader_addURL.invoke(theClassLoader, jsonPack.getValue().getKey().toURI().toURL());
            LOGGER.trace("Added pack folder into URL class loader");
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
                | MalformedURLException e) {
            LOGGER.warn("Cannot load JSON pack into JVM: " + jsonPack.getKey(), e);
            continue;
        }

        Map<String, Object> jsonModInfo = Maps.newHashMap();

        try {
            JsonObject rootObject = jsonPack.getValue().getRight().getAsJsonObject();
            String str = rootObject.get("id").getAsString();
            if (!str.equals("null")) {
                jsonModInfo.put("modid", str);
                jsonModInfo.put("name", rootObject.get("name").getAsString());
                jsonModInfo.put("version", rootObject.get("version").getAsString());
            } else if (Loader.isModLoaded(str)) {
                LOGGER.error("A JSON pack has an ID conflict with another mod!");
                LOGGER.error("If you wish to force an override in here, specify");
                LOGGER.error("conflictOverride:true in the JSON pack info");
                continue;
            }
            //} catch (IOException e) {
            //   LOGGER.warn("A JSON pack info was found and registered but is now unreadable!", e);
            //   continue;
        } catch (JsonParseException e) {
            LOGGER.warn("Syntax errors were found on the JSON file " + jsonPack.getValue().getKey().getName(),
                    e);
            continue;
        }

        List<File> packContents = FSTools.findRecursively(jsonPack.getValue().getKey().getParentFile(),
                TXT_JSON);
        for (File jsonFileToParse : packContents) {

            try {
                LOGGER.debug("Parsing file " + jsonFileToParse.getName());
                final JsonParser theParser = new JsonParser();
                JsonObject root = theParser.parse(new FileReader(jsonFileToParse)).getAsJsonObject();

                String itemType = root.get("type").getAsString();
                JsonObject data = root.get("data").getAsJsonObject();
                if (data != null) {

                    String id = data.get("id").getAsString();
                    int stack_size = data.get("stack_size").getAsInt();
                    String icon = data.get("icons").getAsJsonObject().get("itemIcon").getAsString();

                    JsonArray raw = data.get("names").getAsJsonArray();
                    List<Pair<String, String>> langCodes = Lists.newArrayList();
                    for (JsonElement e : raw) {
                        String s0 = e.getAsString();
                        String[] s1 = s0.split("=", 2);
                        langCodes.add(WeakPair.of(s1[0], s1[1]));
                    }

                    switch (itemType) {
                    case "armor":

                        break;
                    case "tool":

                        break;
                    case "item":

                        Item item = new Item() {

                            public Item setMaxStackSize(int p_77625_1_) {
                                this.maxStackSize = stack_size;
                                return this;
                            }

                            public String getUnlocalizedName() {
                                return "item." + jsonModInfo.get("modid") + "." + id;
                            }

                            public String getUnlocalizedName(ItemStack p_77667_1_) {
                                return getUnlocalizedName();
                            }

                            public void registerIcons(IIconRegister p_94581_1_) {
                                this.itemIcon = p_94581_1_.registerIcon(icon);
                            }

                        };

                        GameRegistry.registerItem(item, item.getUnlocalizedName().substring(5));
                        for (Pair<String, String> pair : langCodes) {
                            LanguageRegistry.instance().addStringLocalization(
                                    item.getUnlocalizedName() + ".name", pair.getKey(), pair.getValue());
                        }
                        break;
                    default:
                        LOGGER.warn("Illegal item type at " + jsonFileToParse.getName());
                    }
                }

            } catch (IOException | JsonParseException | ClassCastException e) {
                LOGGER.warn("Exception caught while parsing file: " + jsonFileToParse.getName(), e);
            }
        }

        FMLModContainer container = new FMLModContainer(XejonLoader.JsonModDelegate.class.getName(),
                new ModCandidate(jsonPack.getRight().getKey(), jsonPack.getValue().getLeft(),
                        ContainerType.DIR),
                jsonModInfo);
        container.bindMetadata(MetadataCollection.from(null, ""));
        FMLClientHandler.instance().addModAsResource(container);
        LOGGER.info("Parser is a work-in-progress. Features may not work as intended if any are loaded.");

    }
}

From source file:alfio.manager.system.DataMigratorIntegrationTest.java

@Test
public void testFixStuckTickets() {
    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, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> eventUsername = initEvent(categories);
    Event event = eventUsername.getKey();
    TicketReservationModification trm = new TicketReservationModification();
    trm.setAmount(1);//www  . j av  a  2  s.  c om
    trm.setTicketCategoryId(eventManager.loadTicketCategories(event).get(0).getId());
    TicketReservationWithOptionalCodeModification r = new TicketReservationWithOptionalCodeModification(trm,
            Optional.empty());
    Date expiration = DateUtils.addDays(new Date(), 1);
    String reservationId = ticketReservationManager.createTicketReservation(event, Collections.singletonList(r),
            Collections.emptyList(), expiration, Optional.empty(), Optional.empty(), Locale.ENGLISH, false);
    //simulate the effect of a reservation cancellation after #392, as described in #391
    ticketReservationRepository.updateReservationStatus(reservationId,
            TicketReservation.TicketReservationStatus.CANCELLED.name());
    List<Ticket> ticketsInReservation = ticketRepository.findTicketsInReservation(reservationId);
    assertEquals(1, ticketsInReservation.size());
    String uuid = ticketsInReservation.get(0).getUuid();
    assertTrue(ticketsInReservation.stream().allMatch(t -> t.getStatus() == Ticket.TicketStatus.PENDING));
    dataMigrator.fixStuckTickets(event.getId());
    assertTrue(ticketRepository.findByUUID(uuid).getStatus() == Ticket.TicketStatus.RELEASED);
}

From source file:alfio.manager.system.DataMigratorIntegrationTest.java

@Test
public void testMigration() {
    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, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> eventUsername = initEvent(categories);
    Event event = eventUsername.getKey();

    try {//from w w w  .  j av a2 s.c  o  m
        eventRepository.updatePrices("CHF", 40, false, BigDecimal.ONE, "STRIPE", event.getId(),
                PriceContainer.VatStatus.NOT_INCLUDED, 1000);

        dataMigrator.migrateEventsToCurrentVersion();
        EventMigration eventMigration = eventMigrationRepository.loadEventMigration(event.getId());
        assertNotNull(eventMigration);
        //assertEquals(buildTimestamp, eventMigration.getBuildTimestamp().toString());
        assertEquals(currentVersion, eventMigration.getCurrentVersion());

        List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
        assertNotNull(tickets);
        assertFalse(tickets.isEmpty());
        assertEquals(AVAILABLE_SEATS, tickets.size());
        assertTrue(tickets.stream().allMatch(t -> t.getCategoryId() == null));
    } finally {
        eventManager.deleteEvent(event.getId(), eventUsername.getValue());
    }
}

From source file:alfio.manager.system.DataMigratorIntegrationTest.java

@Test
public void testMigrationWithExistingRecord() {
    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, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> eventUsername = initEvent(categories);
    Event event = eventUsername.getKey();

    try {//from w w w  .  j a  v  a2s . com
        eventMigrationRepository.insertMigrationData(event.getId(), "1.4",
                ZonedDateTime.now(ZoneId.of("UTC")).minusDays(1), EventMigration.Status.COMPLETE.toString());
        eventRepository.updatePrices("CHF", 40, false, BigDecimal.ONE, "STRIPE", event.getId(),
                PriceContainer.VatStatus.NOT_INCLUDED, 1000);
        dataMigrator.migrateEventsToCurrentVersion();
        EventMigration eventMigration = eventMigrationRepository.loadEventMigration(event.getId());
        assertNotNull(eventMigration);
        //assertEquals(buildTimestamp, eventMigration.getBuildTimestamp().toString());
        assertEquals(currentVersion, eventMigration.getCurrentVersion());

        List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
        assertNotNull(tickets);
        assertFalse(tickets.isEmpty());
        assertEquals(20, tickets.size());
        assertTrue(tickets.stream().allMatch(t -> t.getCategoryId() == null));
    } finally {
        eventManager.deleteEvent(event.getId(), eventUsername.getValue());
    }
}

From source file:alfio.manager.system.DataMigratorIntegrationTest.java

@Test
public void testAlreadyMigratedEvent() {
    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, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> eventUsername = initEvent(categories);
    Event event = eventUsername.getKey();

    try {//from w  ww  .ja  va  2  s .  co  m
        ZonedDateTime migrationTs = ZonedDateTime.now(ZoneId.of("UTC"));
        eventMigrationRepository.insertMigrationData(event.getId(), currentVersion, migrationTs,
                EventMigration.Status.COMPLETE.toString());
        eventRepository.updatePrices("CHF", 40, false, BigDecimal.ONE, "STRIPE", event.getId(),
                PriceContainer.VatStatus.NOT_INCLUDED, 1000);
        dataMigrator.migrateEventsToCurrentVersion();
        EventMigration eventMigration = eventMigrationRepository.loadEventMigration(event.getId());
        assertNotNull(eventMigration);
        //assertEquals(migrationTs.toString(), eventMigration.getBuildTimestamp().toString());
        assertEquals(currentVersion, eventMigration.getCurrentVersion());

        List<Ticket> tickets = ticketRepository.findFreeByEventId(event.getId());
        assertNotNull(tickets);
        assertFalse(tickets.isEmpty());
        assertEquals(AVAILABLE_SEATS, tickets.size());//<-- the migration has not been done
        assertTrue(tickets.stream().allMatch(t -> t.getCategoryId() == null));
    } finally {
        eventManager.deleteEvent(event.getId(), eventUsername.getValue());
    }
}

From source file:alfio.manager.system.DataMigratorIntegrationTest.java

@Test
public void testUpdateDisplayName() {
    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, false, "",
            false, null, null, null, null, null));
    Pair<Event, String> eventUsername = initEvent(categories, null);
    Event event = eventUsername.getKey();

    try {/*from   www.  j a  v a2 s  . co  m*/
        dataMigrator.migrateEventsToCurrentVersion();
        EventMigration eventMigration = eventMigrationRepository.loadEventMigration(event.getId());
        assertNotNull(eventMigration);
        //assertEquals(buildTimestamp, eventMigration.getBuildTimestamp().toString());
        assertEquals(currentVersion, eventMigration.getCurrentVersion());

        Event withDescription = eventRepository.findById(event.getId());
        assertNotNull(withDescription.getDisplayName());
        assertEquals(event.getShortName(), withDescription.getShortName());
        assertEquals(event.getShortName(), withDescription.getDisplayName());
    } finally {
        eventManager.deleteEvent(event.getId(), eventUsername.getValue());
    }
}

From source file:com.act.lcms.db.model.InductionWell.java

public List<InductionWell> insertFromPlateComposition(DB db, PlateCompositionParser parser, Plate p)
        throws SQLException, IOException {
    Map<String, String> plateAttributes = parser.getPlateProperties();
    Map<Pair<String, String>, String> msids = parser.getCompositionTables().get("msid");
    List<Pair<String, String>> sortedCoordinates = new ArrayList<>(msids.keySet());
    Collections.sort(sortedCoordinates, new Comparator<Pair<String, String>>() {
        // TODO: parse the values of these pairs as we read them so we don't need this silly comparator.
        @Override/*from  ww  w.ja va  2  s .  co  m*/
        public int compare(Pair<String, String> o1, Pair<String, String> o2) {
            if (o1.getKey().equals(o2.getKey())) {
                return Integer.valueOf(Integer.parseInt(o1.getValue()))
                        .compareTo(Integer.parseInt(o2.getValue()));
            }
            return o1.getKey().compareTo(o2.getKey());
        }
    });

    List<InductionWell> results = new ArrayList<>();
    for (Pair<String, String> coords : sortedCoordinates) {
        String msid = msids.get(coords);
        if (msid == null || msid.isEmpty()) {
            continue;
        }
        String chemicalSource = parser.getCompositionTables().get("chemical_source").get(coords);
        String composition = parser.getCompositionTables().get("composition").get(coords);
        String chemical = parser.getCompositionTables().get("chemical").get(coords);
        String strainSource = parser.getCompositionTables().get("strain_source").get(coords);
        String note = null;
        if (parser.getCompositionTables().get("note") != null) {
            note = parser.getCompositionTables().get("note").get(coords);
        }

        // TODO: ditch this when we start using floating point numbers for growth values.
        Integer growth = null;
        Map<Pair<String, String>, String> growthTable = parser.getCompositionTables().get("growth");
        if (growthTable == null || growthTable.get(coords) == null) {
            String plateGrowth = plateAttributes.get("growth");
            if (plateGrowth != null) {
                growth = Integer.parseInt(trimAndComplain(plateGrowth));
            }
        } else {
            String growthStr = growthTable.get(coords);
            if (PLUS_MINUS_GROWTH_TO_INT.containsKey(growthStr)) {
                growth = PLUS_MINUS_GROWTH_TO_INT.get(growthStr);
            } else {
                growth = Integer.parseInt(growthStr); // If it's not using +/- format, it should be an integer from 1-5.
            }
        }

        Pair<Integer, Integer> index = parser.getCoordinatesToIndices().get(coords);
        InductionWell s = INSTANCE.insert(db, p.getId(), index.getLeft(), index.getRight(), msid,
                chemicalSource, composition, chemical, strainSource, note, growth);

        results.add(s);
    }

    return results;
}

From source file:com.nextdoor.bender.operation.substitution.formatted.FormattedSubstitution.java

@Override
protected void doSubstitution(InternalEvent ievent, DeserializedEvent devent, Map<String, Object> nested) {
    Object[] values = new Object[this.variables.size()];
    List<String> keyToRemove = new ArrayList<String>();

    for (int i = 0; i < this.variables.size(); i++) {
        Variable<?> variable = this.variables.get(i);

        /*//from w  w w.ja  v a  2  s . c o  m
         * Get values
         */
        if (variable instanceof Variable.FieldVariable) {
            Pair<String, Object> kv = null;
            try {
                kv = getFieldAndSource(devent, ((Variable.FieldVariable) variable).getSrcFields(), true);

                if (((Variable.FieldVariable) variable).getRemoveSrcField()) {
                    keyToRemove.add(kv.getKey());
                }
            } catch (FieldNotFoundException e) {
                if (((Variable.FieldVariable) variable).getFailSrcNotFound()) {
                    throw new OperationException(e);
                }
            }

            if (kv != null) {
                values[i] = kv.getValue();
            } else {
                /*
                 * This handles the case of when fail src not found is false
                 */
                values[i] = null;
            }
        } else if (variable instanceof Variable.StaticVariable) {
            values[i] = ((Variable.StaticVariable) variable).getValue();
        }
    }

    /*
     * Format string with values
     */
    String formatted = format.format(values);

    /*
     * Perform substitution
     */
    if (nested != null) {
        nested.put(this.key, formatted);
        keyToRemove.forEach(fieldName -> {
            if (fieldName.equals(this.key)) {
                return;
            }
            try {
                devent.removeField(fieldName);
            } catch (FieldNotFoundException e) {
            }
        });
        return;
    }

    try {
        devent.setField(this.key, formatted);
    } catch (FieldNotFoundException e) {
        if (this.failDstNotFound) {
            throw new OperationException(e);
        }
    }

    /*
     * Remove source fields
     */
    keyToRemove.forEach(fieldName -> {
        if (fieldName.equals(this.key)) {
            return;
        }
        try {
            devent.removeField(fieldName);
        } catch (FieldNotFoundException e) {
        }
    });
}

From source file:alfio.manager.WaitingQueueProcessorIntegrationTest.java

private Pair<String, Event> initSoldOutEvent(boolean withUnboundedCategory) throws InterruptedException {
    int boundedCategorySize = AVAILABLE_SEATS - (withUnboundedCategory ? 1 : 0);
    List<TicketCategoryModification> categories = new ArrayList<>();
    categories.add(new TicketCategoryModification(null, "default", boundedCategorySize,
            new DateTimeModification(LocalDate.now().minusDays(1), LocalTime.now()),
            new DateTimeModification(LocalDate.now().plusDays(2), LocalTime.now()), DESCRIPTION,
            BigDecimal.ZERO, false, "", true, null, null, null, null, null));

    if (withUnboundedCategory) {
        categories.add(new TicketCategoryModification(null, "unbounded", 0,
                new DateTimeModification(LocalDate.now().minusDays(1), LocalTime.now()),
                new DateTimeModification(LocalDate.now().plusDays(2), LocalTime.now()), DESCRIPTION,
                BigDecimal.ZERO, false, "", false, null, null, null, null, null));
    }/*from  ww  w .j a  v a2 s . c o m*/

    Pair<Event, String> pair = initEvent(categories, organizationRepository, userManager, eventManager,
            eventRepository);
    Event event = pair.getKey();
    List<TicketCategory> ticketCategories = eventManager.loadTicketCategories(event);
    TicketCategory bounded = ticketCategories.stream().filter(t -> t.getName().equals("default")).findFirst()
            .orElseThrow(IllegalStateException::new);
    List<Integer> boundedReserved = ticketRepository.selectFreeTicketsForPreReservation(event.getId(), 20,
            bounded.getId());
    assertEquals(boundedCategorySize, boundedReserved.size());
    List<Integer> reserved = new ArrayList<>(boundedReserved);
    String reservationId = UUID.randomUUID().toString();
    ticketReservationRepository.createNewReservation(reservationId, DateUtils.addHours(new Date(), 1), null,
            Locale.ITALIAN.getLanguage(), event.getId(), event.getVat(), event.isVatIncluded());
    List<Integer> reservedForUpdate = withUnboundedCategory ? reserved.subList(0, 19) : reserved;
    ticketRepository.reserveTickets(reservationId, reservedForUpdate, bounded.getId(),
            Locale.ITALIAN.getLanguage(), 0);
    if (withUnboundedCategory) {
        TicketCategory unbounded = ticketCategories.stream().filter(t -> t.getName().equals("unbounded"))
                .findFirst().orElseThrow(IllegalStateException::new);
        List<Integer> unboundedReserved = ticketRepository
                .selectNotAllocatedFreeTicketsForPreReservation(event.getId(), 20);
        assertEquals(1, unboundedReserved.size());
        reserved.addAll(unboundedReserved);
        ticketRepository.reserveTickets(reservationId, reserved.subList(19, 20), unbounded.getId(),
                Locale.ITALIAN.getLanguage(), 0);
    }
    ticketRepository.updateTicketsStatusWithReservationId(reservationId, Ticket.TicketStatus.ACQUIRED.name());

    //sold-out
    waitingQueueManager.subscribe(event, new CustomerName("Giuseppe Garibaldi", "Giuseppe", "Garibaldi", event),
            "peppino@garibaldi.com", null, Locale.ENGLISH);
    Thread.sleep(100L);//we are testing ordering, not concurrency...
    waitingQueueManager.subscribe(event, new CustomerName("Nino Bixio", "Nino", "Bixio", event),
            "bixio@mille.org", null, Locale.ITALIAN);
    List<WaitingQueueSubscription> subscriptions = waitingQueueRepository.loadAll(event.getId());
    assertTrue(waitingQueueRepository.countWaitingPeople(event.getId()) == 2);
    assertTrue(subscriptions.stream()
            .allMatch(w -> w.getSubscriptionType().equals(WaitingQueueSubscription.Type.SOLD_OUT)));

    //the following call shouldn't have any effect
    waitingQueueSubscriptionProcessor.distributeAvailableSeats(event);
    assertTrue(waitingQueueRepository.countWaitingPeople(event.getId()) == 2);
    return Pair.of(reservationId, event);
}

From source file:lineage2.loginserver.serverpackets.ServerList.java

/**
 * Constructor for ServerList./*from   w ww  .j  ava  2s.c  o m*/
 * @param account Account
 */
public ServerList(Account account) {
    _lastServer = account.getLastServer();
    for (GameServer gs : GameServerManager.getInstance().getGameServers()) {
        InetAddress ip;
        try {
            ip = NetUtils.isInternalIP(account.getLastIP()) ? gs.getInternalHost() : gs.getExternalHost();
        } catch (UnknownHostException e) {
            continue;
        }
        Pair<Integer, int[]> entry = account.getAccountInfo(gs.getId());
        _servers.add(new ServerData(gs.getId(), ip, gs.getPort(), gs.isPvp(), gs.isShowingBrackets(),
                gs.getServerType(), gs.getOnline(), gs.getMaxPlayers(), gs.isOnline(),
                entry == null ? 0 : entry.getKey(), gs.getAgeLimit(),
                entry == null ? ArrayUtils.EMPTY_INT_ARRAY : entry.getValue()));
    }
}