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

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

Introduction

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

Prototype

@Override
public R getValue() 

Source Link

Document

Gets the value from this pair.

This method implements the Map.Entry interface returning the right element as the value.

Usage

From source file:com.galenframework.speclang2.reader.pagespec.PageSectionProcessor.java

private void processSectionRule(PageSection section, StructNode ruleNode) throws IOException {
    String ruleText = ruleNode.getName().substring(1).trim();

    Pair<PageRule, Map<String, String>> rule = findAndProcessRule(ruleText, ruleNode);

    PageSection ruleSection = new PageSection(ruleText);
    section.addSubSection(ruleSection);/*from  w w w.  j ava  2 s  .co m*/

    List<StructNode> resultingNodes;
    try {
        resultingNodes = rule.getKey().apply(pageSpecHandler, ruleText, NO_OBJECT_NAME, rule.getValue());
    } catch (Exception ex) {
        throw new SyntaxException(ruleNode, "Error processing custom rule", ex);
    }
    processSection(ruleSection, resultingNodes);
}

From source file:com.galenframework.speclang2.pagespec.PageSectionProcessor.java

private void processSectionRule(PageSection section, StructNode ruleNode) throws IOException {
    String ruleText = ruleNode.getName().substring(1).trim();

    Pair<PageRule, Map<String, String>> rule = findAndProcessRule(ruleText, ruleNode);

    PageSection ruleSection = new PageSection(ruleText, ruleNode.getPlace());
    section.addSubSection(ruleSection);/*  www.  j a  v  a 2s .com*/

    List<StructNode> resultingNodes;
    try {
        resultingNodes = rule.getKey().apply(pageSpecHandler, ruleText, NO_OBJECT_NAME, rule.getValue(),
                ruleNode.getChildNodes());
        processSection(ruleSection, resultingNodes);
    } catch (Exception ex) {
        throw new SyntaxException(ruleNode, "Error processing rule: " + ruleText, ex);
    }
}

From source file:handlers.voicedcommands.Wedding.java

/**
 * Method engage.//from w  w  w .  j  av a 2  s.  co  m
 * @param activeChar Player
 * @return boolean
 */
private boolean engage(final Player activeChar) {
    if (activeChar.getTarget() == null) {
        activeChar.sendMessage("You have none targeted.");
        return false;
    }

    if (!activeChar.getTarget().isPlayer()) {
        activeChar.sendMessage("You can only ask another Player for partnership.");
        return false;
    }

    if (activeChar.getPartnerId() != 0) {
        activeChar.sendMessage("You are already engaged.");

        if (Config.WEDDING_PUNISH_INFIDELITY) {
            activeChar.startAbnormalEffect(AbnormalEffect.BIG_HEAD);
            int skillId;
            int skillLevel = 1;

            if (activeChar.getLevel() > 40) {
                skillLevel = 2;
            }

            if (activeChar.isMageClass()) {
                skillId = 4361;
            } else {
                skillId = 4362;
            }

            Skill skill = SkillTable.getInstance().getInfo(skillId, skillLevel);

            if (activeChar.getEffectList().getEffectsBySkill(skill) == null) {
                skill.getEffects(activeChar, activeChar, false, false);
                activeChar.sendPacket(new SystemMessage(SystemMessage.S1_S2S_EFFECT_CAN_BE_FELT)
                        .addSkillName(skillId, skillLevel));
            }
        }

        return false;
    }

    final Player ptarget = (Player) activeChar.getTarget();

    if (ptarget.getObjectId() == activeChar.getObjectId()) {
        activeChar.sendMessage("Engaging with yourself?");
        return false;
    }

    if (ptarget.isMaried()) {
        activeChar.sendMessage("Already married.");
        return false;
    }

    if (ptarget.getPartnerId() != 0) {
        activeChar.sendMessage("Is already engaged with someone else.");
        return false;
    }

    Pair<Integer, OnAnswerListener> entry = ptarget.getAskListener(false);

    if ((entry != null) && (entry.getValue() instanceof CoupleAnswerListener)) {
        activeChar.sendMessage("Already asked by someone else.");
        return false;
    }

    if (ptarget.getPartnerId() != 0) {
        activeChar.sendMessage("Is already engaged with someone else.");
        return false;
    }

    if ((ptarget.getSex() == activeChar.getSex()) && !Config.WEDDING_SAMESEX) {
        activeChar.sendMessage("You can't ask partners of same sex.");
        return false;
    }

    boolean FoundOnFriendList = false;
    int objectId;
    Connection con = null;
    PreparedStatement statement = null;
    ResultSet rset = null;

    try {
        con = DatabaseFactory.getInstance().getConnection();
        statement = con.prepareStatement("SELECT friend_id FROM character_friends WHERE char_id=?");
        statement.setInt(1, ptarget.getObjectId());
        rset = statement.executeQuery();

        while (rset.next()) {
            objectId = rset.getInt("friend_id");

            if (objectId == activeChar.getObjectId()) {
                FoundOnFriendList = true;
                break;
            }
        }
    } catch (Exception e) {
        _log.error("", e);
    } finally {
        DbUtils.closeQuietly(con, statement, rset);
    }

    if (!FoundOnFriendList) {
        activeChar.sendMessage("The person you want to ask hasn't added you on the friendlist.");
        return false;
    }

    ConfirmDlg packet = new ConfirmDlg(SystemMsg.S1, 60000).addString(
            "Player " + activeChar.getName() + " asking you to engage. Do you want to start new relationship?");
    ptarget.ask(packet, new CoupleAnswerListener(activeChar, ptarget));
    return true;
}

From source file:alfio.manager.AdminReservationManagerIntegrationTest.java

@Test
public void testReserveFromNewCategory() throws Exception {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 1, 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> 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", "integration-test@test.ch",
            "Billing Address", "en");
    Category category = new Category(null, "name", new BigDecimal("100.00"));
    int attendees = AVAILABLE_SEATS;
    List<TicketsInfo> ticketsInfoList = Collections
            .singletonList(new TicketsInfo(category, generateAttendees(attendees), true, false));
    AdminReservationModification modification = new AdminReservationModification(expiration, customerData,
            ticketsInfoList, "en", false, null);
    Result<Pair<TicketReservation, List<Ticket>>> result = adminReservationManager
            .createReservation(modification, event.getShortName(), username);
    assertTrue(result.isSuccess());//from ww w.  j  a  v a  2s  .co  m
    Pair<TicketReservation, List<Ticket>> data = result.getData();
    List<Ticket> tickets = data.getRight();
    assertTrue(tickets.size() == attendees);
    assertNotNull(data.getLeft());
    int categoryId = tickets.get(0).getCategoryId();
    Event modified = eventManager.getSingleEvent(event.getShortName(), username);
    assertEquals(attendees + 1, eventRepository.countExistingTickets(event.getId()).intValue());
    assertEquals(attendees,
            ticketRepository.findPendingTicketsInCategories(Collections.singletonList(categoryId)).size());
    TicketCategory categoryModified = ticketCategoryRepository.getByIdAndActive(categoryId, event.getId());
    assertEquals(categoryModified.getMaxTickets(), attendees);
    ticketCategoryRepository.findByEventId(event.getId())
            .forEach(tc -> assertTrue(specialPriceRepository.findAllByCategoryId(tc.getId()).stream()
                    .allMatch(sp -> sp.getStatus() == SpecialPrice.Status.PENDING)));
    adminReservationManager.confirmReservation(event.getShortName(), data.getLeft().getId(), username);
    ticketCategoryRepository.findByEventId(event.getId())
            .forEach(tc -> assertTrue(specialPriceRepository.findAllByCategoryId(tc.getId()).stream()
                    .allMatch(sp -> sp.getStatus() == SpecialPrice.Status.TAKEN)));
    assertFalse(ticketRepository.findAllReservationsConfirmedButNotAssigned(event.getId())
            .contains(data.getLeft().getId()));
}

From source file:alfio.manager.AdminReservationManagerIntegrationTest.java

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());/*from   w w  w.j a va2 s. c o  m*/
    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", "integration-test@test.ch",
            "Billing Address", "en");
    Iterator<Integer> attendeesIterator = attendeesNr.iterator();
    List<TicketCategory> existingCategories = ticketCategoryRepository.findByEventId(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, 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(), 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());
}

From source file:com.pgcraft.spectatorplus.guis.SpectatorsToolsGUI.java

@Override
protected void onUpdate() {
    Spectator spectator = SpectatorPlus.get().getPlayerData(getPlayer());

    /* **  -----   Size   -----  ** */

    // We first need to know what is the size of the inventory

    // If a death location is registered for this player, and if every tool is
    // enabled, a line will have to be added.
    // That's why this is defined here, not below.
    // If the "tp to death" tool is disabled, the death location is not set. So it's useless to
    // check this here.

    Location deathPoint = spectator.getDeathLocation();

    int height = 0, offset = 0;
    if (Toggles.TOOLS_TOOLS_SPEED.get()) {
        height++;// www  . j av  a 2 s  . c o  m
        offset = 9;
    }

    if (Toggles.TOOLS_TOOLS_DIVINGSUIT.get() || Toggles.TOOLS_TOOLS_NIGHTVISION.get()
            || Toggles.TOOLS_TOOLS_NOCLIP.get()
            || (Toggles.TOOLS_TOOLS_TPTODEATH_ENABLED.get() && deathPoint != null))
        height++;
    if (Toggles.TOOLS_TOOLS_DIVINGSUIT.get() && Toggles.TOOLS_TOOLS_NIGHTVISION.get()
            && Toggles.TOOLS_TOOLS_NOCLIP.get() && Toggles.TOOLS_TOOLS_TPTODEATH_ENABLED.get()
            && deathPoint != null)
        height++;

    setSize(height * 9);
    setTitle(ChatColor.BLACK + "Spectators' tools");

    /* **  -----   Active tools & effects   -----  ** */

    // Retrieves the current speed level, and the other enabled effects
    // 0 = no speed; 1 = speed I, etc.
    Integer speedLevel = 0;
    Boolean nightVisionActive = false;

    for (PotionEffect effect : getPlayer().getActivePotionEffects()) {
        if (effect.getType().equals(PotionEffectType.SPEED)) {
            speedLevel = effect.getAmplifier() + 1; // +1 because Speed I = amplifier 0.
        } else if (effect.getType().equals(PotionEffectType.NIGHT_VISION)) {
            nightVisionActive = true;
        }
    }

    Boolean divingSuitEquipped = false;
    if (getPlayer().getInventory().getBoots() != null
            && getPlayer().getInventory().getBoots().getType() == Material.DIAMOND_BOOTS) {
        divingSuitEquipped = true;
    }

    List<String> activeLore = Collections.singletonList("" + ChatColor.GRAY + ChatColor.ITALIC + "Active");

    /* **  -----   Speed tools   -----  ** */

    if (Toggles.TOOLS_TOOLS_SPEED.get()) {
        // Normal speed

        ItemStack normalSpeed = GuiUtils.makeItem(Material.STRING, ChatColor.DARK_AQUA + "Normal speed",
                speedLevel == 0 ? activeLore : null);
        if (speedLevel == 0)
            GlowEffect.addGlow(normalSpeed);

        action("speed_0", 2, normalSpeed);

        // Speed I

        ItemStack speedI = GuiUtils.makeItem(Material.FEATHER, ChatColor.AQUA + "Speed I",
                speedLevel == 1 ? activeLore : null);
        if (speedLevel == 1)
            GlowEffect.addGlow(speedI);

        action("speed_1", 3, speedI);

        // Speed II

        ItemStack speedII = GuiUtils.makeItem(Material.FEATHER, ChatColor.AQUA + "Speed II",
                speedLevel == 2 ? activeLore : null);
        speedII.setAmount(2);
        if (speedLevel == 2)
            GlowEffect.addGlow(speedII);

        action("speed_2", 4, speedII);

        // Speed III

        ItemStack speedIII = GuiUtils.makeItem(Material.FEATHER, ChatColor.AQUA + "Speed III",
                speedLevel == 3 ? activeLore : null);
        speedIII.setAmount(3);
        if (speedLevel == 3)
            GlowEffect.addGlow(speedIII);

        action("speed_3", 5, speedIII);

        // Speed IV

        ItemStack speedIV = GuiUtils.makeItem(Material.FEATHER, ChatColor.AQUA + "Speed IV",
                speedLevel == 4 ? activeLore : null);
        speedIV.setAmount(4);
        if (speedLevel == 4)
            GlowEffect.addGlow(speedIV);

        action("speed_4", 6, speedIV);
    }

    /* **  -----   Lines 2 & 3: content   -----  ** */

    List<Pair<String, ItemStack>> toolsOnLine2 = new ArrayList<>();

    // No-clip
    if (Toggles.TOOLS_TOOLS_NOCLIP.get()) {
        ItemStack noClip = GuiUtils.makeItem(Material.BARRIER, ChatColor.LIGHT_PURPLE + "No-clip mode",
                Arrays.asList(ChatColor.GRAY + "Allows you to go through all the blocks.", "",
                        ChatColor.GRAY + "You can also first-spectate a player",
                        ChatColor.GRAY + "by left-clicking on him",
                        ChatColor.DARK_GRAY + "Use Shift to quit the first-person",
                        ChatColor.DARK_GRAY + "spectator mode.", "",
                        ChatColor.DARK_GRAY + "" + ChatColor.ITALIC + "In this mode, open your inventory",
                        ChatColor.DARK_GRAY + "" + ChatColor.ITALIC + "to access controls!"));

        toolsOnLine2.add(Pair.of("noClip", noClip));
    }

    // Night vision
    if (Toggles.TOOLS_TOOLS_NIGHTVISION.get()) {
        ItemStack nightVision = GuiUtils.makeItem(
                nightVisionActive ? Material.EYE_OF_ENDER : Material.ENDER_PEARL,
                nightVisionActive ? ChatColor.DARK_PURPLE + "Disable night vision"
                        : ChatColor.GOLD + "Enable night vision");

        toolsOnLine2.add(Pair.of("nightVision", nightVision));
    }

    // Diving suit
    if (Toggles.TOOLS_TOOLS_DIVINGSUIT.get()) {
        ItemStack divingSuit = GuiUtils.makeItem(Material.DIAMOND_BOOTS, ChatColor.BLUE + "Diving suit",
                Collections.singletonList(ChatColor.GRAY + "Get a pair of Depth Strider III boots"));

        if (divingSuitEquipped) {
            ItemMeta meta = divingSuit.getItemMeta();
            List<String> lore = meta.getLore();
            lore.add(activeLore.get(0));
            meta.setLore(lore);
            divingSuit.setItemMeta(meta);

            GlowEffect.addGlow(divingSuit);
        }

        toolsOnLine2.add(Pair.of("divingSuit", divingSuit));
    }

    // Teleportation to the death point
    ItemStack tpToDeathPoint = null;
    if (Toggles.TOOLS_TOOLS_TPTODEATH_ENABLED.get() && deathPoint != null) {
        tpToDeathPoint = GuiUtils.makeItem(Material.NETHER_STAR, ChatColor.YELLOW + "Go to your death point",
                Toggles.TOOLS_TOOLS_TPTODEATH_DISPLAYCAUSE.get() && spectator.getLastDeathMessage() != null
                        ? Collections.singletonList(ChatColor.GRAY + spectator.getLastDeathMessage())
                        : null);
    }

    /* **  -----   Lines 2 & 3: display   -----  ** */

    int lineSize = toolsOnLine2.size();
    if (lineSize == 0 && deathPoint != null) {
        action("deathPoint", offset + 4, tpToDeathPoint);
    } else if (lineSize == 1) {
        if (deathPoint != null) {
            final Pair<String, ItemStack> toolZero = toolsOnLine2.get(0);

            action(toolZero.getKey(), offset + 2, toolZero.getValue());
            action("deathPoint", offset + 6, tpToDeathPoint);
        } else {
            final Pair<String, ItemStack> toolZero = toolsOnLine2.get(0);
            action(toolZero.getKey(), offset + 4, toolZero.getValue());
        }
    } else if (lineSize == 2) {
        if (deathPoint != null) {
            final Pair<String, ItemStack> toolZero = toolsOnLine2.get(0);
            final Pair<String, ItemStack> toolOne = toolsOnLine2.get(1);

            action(toolZero.getKey(), offset + 2, toolZero.getValue());
            action(toolOne.getKey(), offset + 4, toolOne.getValue());
            action("deathPoint", offset + 6, tpToDeathPoint);
        } else {
            final Pair<String, ItemStack> toolZero = toolsOnLine2.get(0);
            final Pair<String, ItemStack> toolOne = toolsOnLine2.get(1);

            action(toolZero.getKey(), offset + 2, toolZero.getValue());
            action(toolOne.getKey(), offset + 6, toolOne.getValue());
        }
    } else if (lineSize == 3) {
        final Pair<String, ItemStack> toolZero = toolsOnLine2.get(0);
        final Pair<String, ItemStack> toolOne = toolsOnLine2.get(1);
        final Pair<String, ItemStack> toolTwo = toolsOnLine2.get(2);

        action(toolZero.getKey(), offset + 2, toolZero.getValue());
        action(toolOne.getKey(), offset + 4, toolOne.getValue());
        action(toolTwo.getKey(), offset + 6, toolTwo.getValue());

        if (deathPoint != null) {
            action("deathPoint", offset + 6, tpToDeathPoint);
        }
    }
}

From source file:alfio.manager.AdminReservationManagerIntegrationTest.java

@Test
public void testReserveMixed() throws Exception {
    List<TicketCategoryModification> categories = Collections.singletonList(new TicketCategoryModification(null,
            "default", 1, 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> 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", "integration-test@test.ch",
            "Billing Address", "en");

    TicketCategory existingCategory = ticketCategoryRepository.findByEventId(event.getId()).get(0);

    Category resExistingCategory = new Category(existingCategory.getId(), "", existingCategory.getPrice());
    Category resNewCategory = new Category(null, "name", new BigDecimal("100.00"));
    int attendees = 1;
    List<TicketsInfo> ticketsInfoList = Arrays.asList(
            new TicketsInfo(resExistingCategory, generateAttendees(attendees), false, false),
            new TicketsInfo(resNewCategory, generateAttendees(attendees), false, false),
            new TicketsInfo(resExistingCategory, generateAttendees(attendees), false, false));
    AdminReservationModification modification = new AdminReservationModification(expiration, customerData,
            ticketsInfoList, "en", false, null);
    Result<Pair<TicketReservation, List<Ticket>>> result = adminReservationManager
            .createReservation(modification, event.getShortName(), username);
    assertTrue(result.isSuccess());/*from  ww w.  j  av  a2  s .  c o m*/
    Pair<TicketReservation, List<Ticket>> data = result.getData();
    List<Ticket> tickets = data.getRight();
    assertTrue(tickets.size() == 3);
    assertNotNull(data.getLeft());
    assertTrue(tickets.stream().allMatch(t -> t.getTicketsReservationId().equals(data.getKey().getId())));
    int resExistingCategoryId = tickets.get(0).getCategoryId();
    int resNewCategoryId = tickets.get(2).getCategoryId();

    Event modified = eventManager.getSingleEvent(event.getShortName(), username);
    assertEquals(AVAILABLE_SEATS, eventRepository.countExistingTickets(event.getId()).intValue());
    assertEquals(3, ticketRepository
            .findPendingTicketsInCategories(Arrays.asList(resExistingCategoryId, resNewCategoryId)).size());
    assertEquals(3, ticketRepository.findTicketsInReservation(data.getLeft().getId()).size());

    String reservationId = data.getLeft().getId();
    assertEquals(ticketRepository.findTicketsInReservation(reservationId).stream().findFirst().get().getId(),
            ticketRepository.findFirstTicketInReservation(reservationId).get().getId());

    ticketCategoryRepository.findByEventId(event.getId())
            .forEach(tc -> assertTrue(specialPriceRepository.findAllByCategoryId(tc.getId()).stream()
                    .allMatch(sp -> sp.getStatus() == SpecialPrice.Status.PENDING)));
    adminReservationManager.confirmReservation(event.getShortName(), data.getLeft().getId(), username);
    ticketCategoryRepository.findByEventId(event.getId())
            .forEach(tc -> assertTrue(specialPriceRepository.findAllByCategoryId(tc.getId()).stream()
                    .allMatch(sp -> sp.getStatus() == SpecialPrice.Status.TAKEN)));
    assertFalse(ticketRepository.findAllReservationsConfirmedButNotAssigned(event.getId())
            .contains(data.getLeft().getId()));
}

From source file:hu.ppke.itk.nlpg.purepos.decoder.AbstractDecoder.java

protected List<Pair<List<Integer>, Double>> cleanResults(List<Pair<List<Integer>, Double>> tagSeqList) {
    List<Pair<List<Integer>, Double>> ret = new ArrayList<Pair<List<Integer>, Double>>();
    for (Pair<List<Integer>, Double> element : tagSeqList) {
        List<Integer> tagSeq = element.getKey();
        List<Integer> newTagSeq = tagSeq.subList(0, tagSeq.size() - 1);
        ret.add(Pair.of(newTagSeq, element.getValue()));
    }//w  w  w.j  av  a  2s.  c om
    return ret;
}

From source file:com.samsung.sjs.backend.CBackend.java

/**
 * Returns a new ID for a new vtable, or the id of an existing
 * vtable if argument vt is identical to a previous vtable array.
 *//*from w  w  w.j  a va2 s.c o m*/
protected int memo_vtable(int[] vt) {
    int result = -1;
    int hash = Arrays.hashCode(vt);
    int oldsize = vtables_by_hash.size();
    int oldsetsize = -1;
    boolean collision = false;
    if (vtables_by_hash.containsKey(hash)) {
        Set<Pair<int[], Integer>> possible_matches = vtables_by_hash.get(hash);
        assert (possible_matches != null);
        for (Pair<int[], Integer> test : possible_matches) {
            if (Arrays.equals(test.getKey(), vt)) {
                collision = true;
                result = test.getValue();
            }
        }
        if (!collision) {
            // We hit an existing has bucket, but don't match
            result = next_vtable_id++;
            Pair<int[], Integer> newpair = Pair.of(vt, result);
            oldsetsize = possible_matches.size();
            possible_matches.add(newpair);
            assert (possible_matches.size() > oldsetsize);
        }
    } else {
        // We don't match any existing bucket
        result = next_vtable_id++;
        Pair<int[], Integer> newpair = Pair.of(vt, result);
        Set<Pair<int[], Integer>> newset = new HashSet<Pair<int[], Integer>>();
        newset.add(newpair);
        vtables_by_hash.put(hash, newset);
        assert (vtables_by_hash.size() >= oldsize);
    }
    assert (result >= 0); // we initialize next_vtable_id to 0, so -1 is invalid
    return result;
}

From source file:it.anyplace.sync.client.SyncthingClient.java

public FileDownloadObserver pullFile(BlockExchangeConnectionHandler connectionHandler, String folder,
        String path) throws InterruptedException {
    Pair<FileInfo, FileBlocks> fileInfoAndBlocks = indexHandler.waitForRemoteIndexAquired(connectionHandler)
            .getFileInfoAndBlocksByPath(folder, path);
    checkNotNull(fileInfoAndBlocks, "file not found in local index for folder = %s path = %s", folder, path);
    return new BlockPuller(configuration, connectionHandler).pullBlocks(fileInfoAndBlocks.getValue());
}