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

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

Introduction

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

Prototype

public abstract R getRight();

Source Link

Document

Gets the right element from this pair.

When treated as a key-value pair, this is the value.

Usage

From source file:malte0811.industrialWires.blocks.wire.TileEntityIC2ConnectorTin.java

public void transferPower() {
    Set<AbstractConnection> conns = new HashSet<>(
            ImmersiveNetHandler.INSTANCE.getIndirectEnergyConnections(pos, worldObj));
    Map<AbstractConnection, Pair<IIC2Connector, Double>> maxOutputs = new HashMap<>();
    double outputMax = Math.min(inBuffer, maxToNet);
    double sum = 0;
    for (AbstractConnection c : conns) {
        IImmersiveConnectable iic = ApiUtils.toIIC(c.end, worldObj);
        if (iic instanceof IIC2Connector) {
            double tmp = inBuffer - ((IIC2Connector) iic).insertEnergy(outputMax, true);
            if (tmp > .00000001) {
                maxOutputs.put(c, new ImmutablePair<>((IIC2Connector) iic, tmp));
                sum += tmp;/*ww  w .j a va  2  s.  co m*/
            }
        }
    }
    if (sum < .0001) {
        return;
    }
    final double oldInBuf = outputMax;
    HashMap<Connection, Integer> transferedPerConn = ImmersiveNetHandler.INSTANCE
            .getTransferedRates(worldObj.provider.getDimension());
    for (AbstractConnection c : maxOutputs.keySet()) {
        Pair<IIC2Connector, Double> p = maxOutputs.get(c);
        double out = oldInBuf * p.getRight() / sum;
        double loss = getAverageLossRate(c);
        double inserted = out - p.getLeft().insertEnergy(out - loss, false);
        inBuffer -= inserted;
        float intermediaryLoss = 0;
        HashSet<IImmersiveConnectable> passedConnectors = new HashSet<>();
        double energyAtConn = inserted + loss;
        for (Connection sub : c.subConnections) {
            int transferredPerCon = transferedPerConn.containsKey(sub) ? transferedPerConn.get(sub) : 0;
            energyAtConn -= sub.cableType.getLossRatio() * sub.length;
            ImmersiveNetHandler.INSTANCE.getTransferedRates(worldObj.provider.getDimension()).put(sub,
                    (int) (transferredPerCon + energyAtConn));
            IImmersiveConnectable subStart = ApiUtils.toIIC(sub.start, worldObj);
            IImmersiveConnectable subEnd = ApiUtils.toIIC(sub.end, worldObj);
            if (subStart != null && passedConnectors.add(subStart))
                subStart.onEnergyPassthrough((int) (inserted - inserted * intermediaryLoss));
            if (subEnd != null && passedConnectors.add(subEnd))
                subEnd.onEnergyPassthrough((int) (inserted - inserted * intermediaryLoss));
        }
    }
}

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  w w  w . j a  v a 2 s . c o 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:com.devicehive.resource.impl.DeviceNotificationResourceImpl.java

private void poll(final long timeout, final String deviceGuidsString, final String namesString,
        final String timestamp, final AsyncResponse asyncResponse) throws InterruptedException {
    final HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();//from   w w w.ja v a2 s  . c  o m
    final Date ts = TimestampQueryParamParser
            .parse(timestamp == null ? timestampService.getDateAsString() : timestamp);

    final Response response = ResponseFactory.response(Response.Status.OK, Collections.emptyList(),
            JsonPolicyDef.Policy.NOTIFICATION_TO_CLIENT);

    asyncResponse.setTimeoutHandler(asyncRes -> asyncRes.resume(response));

    Set<String> availableDevices;
    if (deviceGuidsString == null) {
        availableDevices = deviceService.findByGuidWithPermissionsCheck(Collections.emptyList(), principal)
                .stream().map(DeviceVO::getGuid).collect(Collectors.toSet());

    } else {
        availableDevices = Optional.ofNullable(StringUtils.split(deviceGuidsString, ',')).map(Arrays::asList)
                .map(list -> deviceService.findByGuidWithPermissionsCheck(list, principal))
                .map(list -> list.stream().map(DeviceVO::getGuid).collect(Collectors.toSet()))
                .orElse(Collections.emptySet());
    }

    Set<String> notifications = Optional.ofNullable(StringUtils.split(namesString, ',')).map(Arrays::asList)
            .map(list -> list.stream().collect(Collectors.toSet())).orElse(Collections.emptySet());

    BiConsumer<DeviceNotification, String> callback = (notification, subscriptionId) -> {
        if (!asyncResponse.isDone()) {
            asyncResponse.resume(ResponseFactory.response(Response.Status.OK,
                    Collections.singleton(notification), JsonPolicyDef.Policy.NOTIFICATION_TO_CLIENT));
        }
    };

    if (!availableDevices.isEmpty()) {
        Pair<String, CompletableFuture<List<DeviceNotification>>> pair = notificationService
                .subscribe(availableDevices, notifications, ts, callback);
        pair.getRight().thenAccept(collection -> {
            if (!collection.isEmpty() && !asyncResponse.isDone()) {
                asyncResponse.resume(ResponseFactory.response(Response.Status.OK, collection,
                        JsonPolicyDef.Policy.NOTIFICATION_TO_CLIENT));
            }

            if (timeout == 0) {
                asyncResponse.setTimeout(1, TimeUnit.MILLISECONDS); // setting timeout to 0 would cause
                // the thread to suspend indefinitely, see AsyncResponse docs
            } else {
                asyncResponse.setTimeout(timeout, TimeUnit.SECONDS);
            }
        });

        asyncResponse.register(new CompletionCallback() {
            @Override
            public void onComplete(Throwable throwable) {
                notificationService.unsubscribe(pair.getLeft(), null);
            }
        });
    } else {
        if (!asyncResponse.isDone()) {
            asyncResponse.resume(response);
        }
    }
}

From source file:edu.upenn.cis.stormlite.LocalCluster.java

/**
 * For each spout in the topology, create multiple objects (according to the parallelism)
 * /*  w  w  w  . j  ava  2s  .c om*/
 * @param topo Topology
 */
private void createSpoutInstances(Topology topo, Config config) {
    for (String key : topo.getSpouts().keySet()) {
        Pair<Class<? extends IRichSpout>, Integer> spout = topo.getSpout(key);

        SpoutOutputCollector collector = new SpoutOutputCollector(context);

        spoutStreams.put(key, new ArrayList<IRichSpout>());
        for (int i = 0; i < spout.getRight(); i++)
            try {
                IRichSpout newSpout = spout.getLeft().newInstance();

                newSpout.open(config, context, collector);
                spoutStreams.get(key).add(newSpout);
                log.debug("Created a spout executor " + key + "/" + newSpout.getExecutorId() + " of type "
                        + spout.getLeft().getName());
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
}

From source file:edu.ksu.cis.santos.mdcf.dms.test.SymbolTableTest.java

<T extends Member> void allMembers(final Class<T> clazz) throws Exception {
    final SymbolTable st = SymbolTableTest.ST;
    final StringBuilder sb = new StringBuilder();

    final String className = clazz.getSimpleName();

    final String title = "All (Declared and Inherited) " + className + "s";
    appendln(sb, title);//from  w  w  w  .  j a v a  2s  . c o m
    for (int i = 0; i < title.length(); i++) {
        sb.append('=');
    }
    appendln(sb);

    final Set<String> featureNames = featureOrDeviceNames();

    for (final String featureName : featureNames) {
        appendln(sb);
        sb.append("* ");
        sb.append(shorten(featureName));
        sb.append(": ");
        final Collection<Pair<Feature, T>> c = st.filterp(st.allMemberMap(featureName), clazz).values();
        for (final Pair<Feature, T> p : c) {
            sb.append('(');
            sb.append(shorten(p.getLeft().name));
            sb.append(", ");
            final Member right = p.getRight();
            sb.append(right instanceof Attribute ? "attr:" : "inv:");
            sb.append(right.name);
            sb.append("), ");
        }
        deleteLastChars(sb, 2);
    }

    testExpectedResult("dms.test.symbol.all" + className.toLowerCase() + "s", sb.toString());
}

From source file:cn.liutils.vis.animation.CubicSplineCurve.java

private double kval(int index) {
    Pair<Double, Double> pt1 = null, pt2 = null, pt3 = null;

    boolean flag = false;
    if (index == 0) {
        pt1 = pts.get(0);/*from  w  ww  .j a  v a 2 s  .  co m*/
        pt2 = pts.get(1);
        flag = true;
    }
    if (index == pts.size() - 1) {
        pt1 = pts.get(pts.size() - 2);
        pt2 = pts.get(index);
        flag = true;
    }
    if (flag)
        return (pt2.getRight() - pt1.getRight()) / (pt2.getLeft() - pt1.getLeft());

    pt1 = pts.get(index - 1);
    pt2 = pts.get(index);
    pt3 = pts.get(index + 1);

    return ((pt2.getRight() - pt1.getRight()) / (pt2.getLeft() - pt1.getLeft())
            + (pt3.getRight() - pt2.getRight()) / (pt3.getLeft() - pt2.getLeft())) / 2;
}

From source file:com.ottogroup.bi.streaming.operator.json.insert.JsonStaticContentInsertion.java

public JsonStaticContentInsertion(final List<Pair<JsonContentReference, Serializable>> values)
        throws IllegalArgumentException {

    ///////////////////////////////////////////////////////
    // validate input
    if (values == null) // empty input "configures" the operator to work as simple "pass-through" operator
        throw new IllegalArgumentException("Missing required input");
    ///////////////////////////////////////////////////////

    for (final Pair<JsonContentReference, Serializable> v : values) {
        if (v == null)
            throw new IllegalArgumentException("Empty list elements are not permitted");
        if (v.getLeft() == null || v.getKey().getPath() == null || v.getKey().getPath().length < 1)
            throw new IllegalArgumentException("Empty content referenced are not permitted");
        if (v.getRight() == null)
            throw new IllegalArgumentException("Null is not permitted as insertion value");
        this.values.add(v);
    }//from w  w  w  . j a v  a  2 s.co  m
}

From source file:net.community.chest.gitcloud.facade.AbstractEnvironmentInitializer.java

protected void contextInitialized(ServletContext context) {
    PlaceholderResolver contextResolver = ServletUtils.toPlaceholderResolver(context);
    Pair<File, Boolean> result = ConfigUtils.resolveGitcloudBase(new AggregatedExtendedPlaceholderResolver(
            contextResolver, ExtendedPlaceholderResolverUtils.SYSPROPS_RESOLVER,
            ExtendedPlaceholderResolverUtils.ENVIRON_RESOLVER));
    File rootDir = result.getLeft();
    Boolean baseExists = result.getRight();
    if (!baseExists.booleanValue()) {
        System.setProperty(ConfigUtils.GITCLOUD_BASE_PROP, rootDir.getAbsolutePath());
        logger.info("contextInitialized(" + context.getContextPath() + ") - added "
                + ConfigUtils.GITCLOUD_BASE_PROP + ": " + ExtendedFileUtils.toString(rootDir));
    } else {//from   w ww.  j  ava 2s  .  co m
        logger.info("contextInitialized(" + context.getContextPath() + ") using "
                + ConfigUtils.GITCLOUD_BASE_PROP + ": " + ExtendedFileUtils.toString(rootDir));
    }

    extractConfigFiles(new File(rootDir, ConfigUtils.CONF_DIR_NAME));
}

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

public List<DeliveredStrainWell> insertFromPlateComposition(DB db, PlateCompositionParser parser, Plate p)
        throws SQLException, IOException {
    List<DeliveredStrainWell> results = new ArrayList<>();

    Map<Pair<String, String>, String> featuresTable = parser.getCompositionTables().get("well");
    /* The composition tables are usually constructed with well coordinates as the X and Y axes.  Amyris strain plates,
     * however, have the combined well coordinates in the first column and the msid/composition in related columns.
     * We'll collect the features in each row by traversing the per-cell entries in the parser's table and merging on
     * the first coordinate component. */
    Map<Pair<Integer, Integer>, Map<String, String>> wellToFeaturesMap = new HashMap<>();
    for (Map.Entry<Pair<String, String>, String> entry : featuresTable.entrySet()) {
        String wellCoordinates = entry.getKey().getLeft();
        String featureName = entry.getKey().getRight();
        String featureValue = entry.getValue();

        Pair<Integer, Integer> coordinates = Utils.parsePlateCoordinates(wellCoordinates);

        Map<String, String> featuresForWell = wellToFeaturesMap.get(coordinates);
        if (featuresForWell == null) {
            featuresForWell = new HashMap<>();
            wellToFeaturesMap.put(coordinates, featuresForWell);
        }/*from ww w.  ja v a 2  s . co  m*/
        if (featuresForWell.containsKey(featureName)) {
            throw new RuntimeException(
                    String.format("Found duplicate feature %s for well %s", wellCoordinates, featureName));
        }
        featuresForWell.put(featureName, featureValue);
        // Also save the original well coordinates string.
        featuresForWell.put("well", wellCoordinates);
    }

    List<Map.Entry<Pair<Integer, Integer>, Map<String, String>>> sortedEntries = new ArrayList<>(
            wellToFeaturesMap.entrySet());
    Collections.sort(sortedEntries, new Comparator<Map.Entry<Pair<Integer, Integer>, Map<String, String>>>() {
        @Override
        public int compare(Map.Entry<Pair<Integer, Integer>, Map<String, String>> o1,
                Map.Entry<Pair<Integer, Integer>, Map<String, String>> o2) {
            return o1.getKey().compareTo(o2.getKey());
        }
    });

    for (Map.Entry<Pair<Integer, Integer>, Map<String, String>> entry : sortedEntries) {
        Pair<Integer, Integer> coords = entry.getKey();
        Map<String, String> attrs = entry.getValue();
        DeliveredStrainWell s = INSTANCE.insert(db, p.getId(), coords.getLeft(), coords.getRight(),
                attrs.get("well"), attrs.get("msid"), attrs.get("composition"));
        results.add(s);
    }

    return results;
}

From source file:com.dgtlrepublic.anitomyj.Tokenizer.java

/** Tokenize by bracket. */
private void tokenizeByBrackets() {
    /** a ref to the closing brace of a found opening brace. (e.g "}" if we found an "}") */
    AtomicReference<String> matchingBracket = new AtomicReference<>();

    /** function to find an opening brace */
    BiFunction<Integer, Integer, Integer> findFirstBracket = (start, end) -> {
        for (int i = start; i < end; i++) {
            for (Pair<String, String> bracket : brackets) {
                if (String.valueOf(filename.charAt(i)).equals(bracket.getLeft())) {
                    matchingBracket.set(bracket.getRight());
                    return i;
                }/*from w w  w .  j  av a 2 s .c  o  m*/
            }
        }

        return -1;
    };

    boolean isBracketOpen = false;
    for (int i = 0; i < filename.length();) {
        int foundIdx;
        if (!isBracketOpen) {
            /** look for opening brace */
            foundIdx = findFirstBracket.apply(i, filename.length());
        } else {
            /** look for closing brace */
            foundIdx = filename.indexOf(matchingBracket.get(), i);
        }

        TokenRange range = new TokenRange(i, foundIdx == -1 ? filename.length() : foundIdx - i);
        if (range.getSize() > 0) {
            /** check if our range contains any known anime identifies */
            tokenizeByPreidentified(isBracketOpen, range);
        }

        if (foundIdx != -1) {
            /** mark as bracket */
            addToken(TokenCategory.kBracket, true, new TokenRange(range.getOffset() + range.getSize(), 1));
            isBracketOpen = !isBracketOpen;
            i = foundIdx + 1;
        } else {
            break;
        }
    }
}