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

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

Introduction

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

Prototype

public abstract L getLeft();

Source Link

Document

Gets the left element from this pair.

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

Usage

From source file:at.gridtec.lambda4j.function.bi.to.ToLongBiFunction2.java

/**
 * Applies this function to the given tuple.
 *
 * @param tuple The tuple to be applied to the function
 * @return The return value from the function, which is its result.
 * @throws NullPointerException If given argument is {@code null}
 * @see org.apache.commons.lang3.tuple.Pair
 *//*from www .  ja v  a 2s  . co  m*/
default long applyAsLong(@Nonnull Pair<T, U> tuple) {
    Objects.requireNonNull(tuple);
    return applyAsLong(tuple.getLeft(), tuple.getRight());
}

From source file:com.mirth.connect.server.migration.ServerMigrator.java

private void runConfigurationMigrator(ConfigurationMigrator configurationMigrator,
        PropertiesConfiguration mirthConfig, Version version) {
    configurationMigrator.updateConfiguration(mirthConfig);

    HashMap<String, Object> addedProperties = new LinkedHashMap<String, Object>();
    Map<String, Object> propertiesToAdd = configurationMigrator.getConfigurationPropertiesToAdd();

    if (propertiesToAdd != null) {
        for (Entry<String, Object> propertyToAdd : propertiesToAdd.entrySet()) {
            if (!mirthConfig.containsKey(propertyToAdd.getKey())) {
                PropertiesConfigurationLayout layout = mirthConfig.getLayout();
                String key = propertyToAdd.getKey();
                Object value;//from   w  ww .ja  v  a2  s .  com
                String comment = "";

                if (propertyToAdd.getValue() instanceof Pair) {
                    // If a pair is used, get both the value and comment
                    Pair<Object, String> pair = (Pair<Object, String>) propertyToAdd.getValue();
                    value = pair.getLeft();
                    comment = pair.getRight();
                } else {
                    // Only the value was specified
                    value = propertyToAdd.getValue();
                }

                mirthConfig.setProperty(key, value);

                // If this is the first added property, add a general comment about the added properties before it
                if (addedProperties.isEmpty()) {
                    if (StringUtils.isNotEmpty(comment)) {
                        comment = "\n\n" + comment;
                    }
                    comment = "The following properties were automatically added on startup for version "
                            + version + comment;
                }

                if (StringUtils.isNotEmpty(comment)) {
                    // When a comment is specified, always put a blank line before it
                    layout.setBlancLinesBefore(key, 1);
                    layout.setComment(key, comment);
                }

                addedProperties.put(key, value);
            }
        }
    }

    List<String> removedProperties = new ArrayList<String>();
    String[] propertiesToRemove = configurationMigrator.getConfigurationPropertiesToRemove();

    if (propertiesToRemove != null) {
        for (String propertyToRemove : propertiesToRemove) {
            if (mirthConfig.containsKey(propertyToRemove)) {
                mirthConfig.clearProperty(propertyToRemove);
                removedProperties.add(propertyToRemove);
            }
        }
    }

    if (!addedProperties.isEmpty() || !removedProperties.isEmpty()) {
        if (!addedProperties.isEmpty()) {
            logger.info("Adding properties in mirth.properties: " + addedProperties);
        }

        if (!removedProperties.isEmpty()) {
            logger.info("Removing properties in mirth.properties: " + removedProperties);
        }

        try {
            mirthConfig.save();
        } catch (ConfigurationException e) {
            logger.error("There was an error updating mirth.properties.", e);

            if (!addedProperties.isEmpty()) {
                logger.error("The following properties should be added to mirth.properties manually: "
                        + addedProperties.toString());
            }

            if (!removedProperties.isEmpty()) {
                logger.error("The following properties should be removed from mirth.properties manually: "
                        + removedProperties.toString());
            }
        }
    }
}

From source file:com.twitter.distributedlog.client.proxy.TestProxyClientManager.java

@Test(timeout = 60000)
public void testHandshake() throws Exception {
    final int numHosts = 3;
    final int numStreamsPerHost = 3;
    final int initialPort = 4000;

    MockProxyClientBuilder builder = new MockProxyClientBuilder();
    Map<SocketAddress, ServerInfo> serverInfoMap = new HashMap<SocketAddress, ServerInfo>();
    for (int i = 0; i < numHosts; i++) {
        SocketAddress address = createSocketAddress(initialPort + i);
        ServerInfo serverInfo = new ServerInfo();
        for (int j = 0; j < numStreamsPerHost; j++) {
            serverInfo.putToOwnerships(runtime.getMethodName() + "_stream_" + j, address.toString());
        }/*  w  w w.  java2s. co  m*/
        Pair<MockProxyClient, MockServerInfoService> mockProxyClient = createMockProxyClient(address,
                serverInfo);
        builder.provideProxyClient(address, mockProxyClient.getLeft());
        serverInfoMap.put(address, serverInfo);
    }

    final Map<SocketAddress, ServerInfo> results = new HashMap<SocketAddress, ServerInfo>();
    final CountDownLatch doneLatch = new CountDownLatch(2 * numHosts);
    ProxyListener listener = new ProxyListener() {
        @Override
        public void onHandshakeSuccess(SocketAddress address, ProxyClient client, ServerInfo serverInfo) {
            synchronized (results) {
                results.put(address, serverInfo);
            }
            doneLatch.countDown();
        }

        @Override
        public void onHandshakeFailure(SocketAddress address, ProxyClient client, Throwable cause) {
        }
    };

    TestHostProvider rs = new TestHostProvider();
    ProxyClientManager clientManager = createProxyClientManager(builder, rs, 0L);
    clientManager.registerProxyListener(listener);
    assertEquals("There should be no clients in the manager", 0, clientManager.getNumProxies());
    for (int i = 0; i < numHosts; i++) {
        rs.addHost(createSocketAddress(initialPort + i));
    }
    // handshake would handshake with 3 hosts again
    clientManager.handshake();
    doneLatch.await();
    assertEquals("Handshake should return server info", numHosts, results.size());
    assertTrue("Handshake should get all server infos", Maps.difference(serverInfoMap, results).areEqual());
}

From source file:com.vmware.photon.controller.apife.backends.ProjectSqlBackend.java

@Override
@Transactional/*from  w  ww  .  j  a v  a2s.  c  o m*/
public TaskEntity setSecurityGroups(String projectId, List<String> securityGroups) throws ExternalException {

    logger.info("Updating the security groups of project {} to {}", projectId, securityGroups.toString());

    ProjectEntity projectEntity = findById(projectId);

    List<SecurityGroup> currSecurityGroups = SecurityGroupUtils
            .toApiRepresentation(projectEntity.getSecurityGroups());
    Pair<List<SecurityGroup>, List<String>> result = SecurityGroupUtils
            .mergeSelfSecurityGroups(currSecurityGroups, securityGroups);

    replaceSecurityGroups(projectId, result.getLeft());

    TaskEntity taskEntity = taskBackend.createCompletedTask(projectEntity,
            Operation.SET_PROJECT_SECURITY_GROUPS);
    StepEntity stepEntity = taskBackend.getStepBackend().createCompletedStep(taskEntity, projectEntity,
            Operation.SET_PROJECT_SECURITY_GROUPS);

    if (!result.getRight().isEmpty()) {
        stepEntity.addWarning(new SecurityGroupsAlreadyInheritedException(result.getRight()));
    }

    return taskEntity;
}

From source file:de.ellpeck.actuallyadditions.mod.items.ItemFillingWand.java

@Override
public void onUpdate(ItemStack stack, World world, Entity entity, int itemSlot, boolean isSelected) {
    super.onUpdate(stack, world, entity, itemSlot, isSelected);

    if (!world.isRemote) {
        boolean shouldClear = false;

        if (isSelected) {
            if (entity instanceof EntityPlayer && stack.hasTagCompound()) {
                EntityPlayer player = (EntityPlayer) entity;
                boolean creative = player.capabilities.isCreativeMode;

                NBTTagCompound compound = stack.getTagCompound();

                BlockPos firstPos = new BlockPos(compound.getInteger("FirstX"), compound.getInteger("FirstY"),
                        compound.getInteger("FirstZ"));
                BlockPos secondPos = new BlockPos(compound.getInteger("SecondX"),
                        compound.getInteger("SecondY"), compound.getInteger("SecondZ"));

                if (!BlockPos.ORIGIN.equals(firstPos) && !BlockPos.ORIGIN.equals(secondPos)) {
                    int energyUse = 1500;

                    Pair<IBlockState, String> data = loadData(stack);
                    if (data != null && (creative || this.getEnergyStored(stack) >= energyUse)) {
                        IBlockState replaceState = data.getLeft();
                        int lowestX = Math.min(firstPos.getX(), secondPos.getX());
                        int lowestY = Math.min(firstPos.getY(), secondPos.getY());
                        int lowestZ = Math.min(firstPos.getZ(), secondPos.getZ());

                        int currX = compound.getInteger("CurrX");
                        int currY = compound.getInteger("CurrY");
                        int currZ = compound.getInteger("CurrZ");

                        BlockPos pos = new BlockPos(lowestX + currX, lowestY + currY, lowestZ + currZ);
                        IBlockState state = world.getBlockState(pos);

                        if (state.getBlock().isReplaceable(world, pos)
                                && replaceState.getBlock().canPlaceBlockAt(world, pos)) {
                            if (creative || removeFittingItem(replaceState, player)) {
                                world.setBlockState(pos, replaceState, 2);

                                SoundType sound = replaceState.getBlock().getSoundType(replaceState, world, pos,
                                        player);
                                world.playSound(null, pos, sound.getPlaceSound(), SoundCategory.BLOCKS,
                                        sound.getVolume() / 2F + .5F, sound.getPitch() * 0.8F);

                                if (!creative) {
                                    this.extractEnergyInternal(stack, energyUse, false);
                                }//from  w w w .j  a v  a  2 s. co m
                            } else {
                                shouldClear = true;
                            }
                        }

                        int distX = Math.abs(secondPos.getX() - firstPos.getX());
                        int distY = Math.abs(secondPos.getY() - firstPos.getY());
                        int distZ = Math.abs(secondPos.getZ() - firstPos.getZ());

                        currX++;
                        if (currX > distX) {
                            currX = 0;
                            currY++;
                            if (currY > distY) {
                                currY = 0;
                                currZ++;
                                if (currZ > distZ) {
                                    shouldClear = true;
                                }
                            }
                        }

                        if (!shouldClear) {
                            compound.setInteger("CurrX", currX);
                            compound.setInteger("CurrY", currY);
                            compound.setInteger("CurrZ", currZ);
                        }
                    } else {
                        shouldClear = true;
                    }
                }
            }
        } else {
            shouldClear = true;
        }

        if (shouldClear) {
            ItemPhantomConnector.clearStorage(stack, "FirstX", "FirstY", "FirstZ", "SecondX", "SecondY",
                    "SecondZ", "CurrX", "CurrY", "CurrZ");
        }
    }
}

From source file:at.gridtec.lambda4j.function.bi.to.ToDoubleBiFunction2.java

/**
 * Applies this function to the given tuple.
 *
 * @param tuple The tuple to be applied to the function
 * @return The return value from the function, which is its result.
 * @throws NullPointerException If given argument is {@code null}
 * @see org.apache.commons.lang3.tuple.Pair
 *//*from   w w w  .  java2 s . c  o  m*/
default double applyAsDouble(@Nonnull Pair<T, U> tuple) {
    Objects.requireNonNull(tuple);
    return applyAsDouble(tuple.getLeft(), tuple.getRight());
}

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/*w w w . ja  v  a 2 s.c  om*/
        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.yahoo.pulsar.common.naming.NamespaceBundlesTest.java

private void assertBundles(NamespaceBundleFactory utilityFactory, NamespaceName nsname, NamespaceBundle bundle,
        Pair<NamespaceBundles, List<NamespaceBundle>> splitBundles, int numBundles) throws Exception {

    NamespaceBundle bundle1 = splitBundles.getRight().get(0);
    NamespaceBundle bundle2 = splitBundles.getRight().get(1);

    NamespaceBundles nspaceBundles = splitBundles.getLeft();
    Pair<NamespaceBundles, List<NamespaceBundle>> bundle1Split = splitBundlesUtilFactory(utilityFactory, nsname,
            nspaceBundles, bundle1, numBundles);
    assertBundleDivideInTwo(bundle1, bundle1Split.getRight(), numBundles);

    Pair<NamespaceBundles, List<NamespaceBundle>> bundle2Split = splitBundlesUtilFactory(utilityFactory, nsname,
            nspaceBundles, bundle2, numBundles);
    assertBundleDivideInTwo(bundle2, bundle2Split.getRight(), numBundles);

}

From source file:fredboat.audio.player.GuildPlayer.java

public void skipTracksForMemberPerms(CommandContext context, Collection<Long> trackIds, String successMessage) {
    Pair<Boolean, String> pair = canMemberSkipTracks(context.invoker, trackIds);

    if (pair.getLeft()) {
        context.reply(successMessage);//from ww  w . j a v  a2  s .co m
        skipTracks(trackIds);
    } else {
        context.replyWithName(pair.getRight());
    }
}

From source file:com.act.lcms.MS2Simple.java

private void plot(List<Pair<MS2Collected, Integer>> ms2Spectra, Double mz, List<Double> ms2SearchMZs,
        String outPrefix, String fmt) throws IOException {
    String outPDF = outPrefix + "." + fmt;
    String outDATA = outPrefix + ".data";

    // Write data output to outfile
    PrintStream out = new PrintStream(new FileOutputStream(outDATA));

    List<String> plotID = new ArrayList<>(ms2Spectra.size());
    for (Pair<MS2Collected, Integer> pair : ms2Spectra) {
        MS2Collected yzSlice = pair.getLeft();
        String caption;/*from  w  ww .j a  va  2 s .co m*/
        if (ms2SearchMZs != null && ms2SearchMZs.size() > 0) {
            caption = String.format("target: %.4f, time: %.4f, volts: %.4f, %d / %d matches",
                    yzSlice.triggerMass, yzSlice.triggerTime, yzSlice.voltage,
                    pair.getRight() == null ? 0 : pair.getRight(), ms2SearchMZs.size());
        } else {
            caption = String.format("target: %.4f, time: %.4f, volts: %.4f", yzSlice.triggerMass,
                    yzSlice.triggerTime, yzSlice.voltage);
        }
        plotID.add(caption);
        // Compute the total intensity on the fly so we can plot on a percentage scale.
        double maxIntensity = 0.0;
        for (YZ yz : yzSlice.ms2) {
            if (yz.intensity > maxIntensity) {
                maxIntensity = yz.intensity;
            }
        }
        // print out the spectra to outDATA
        for (YZ yz : yzSlice.ms2) {
            out.format("%.4f\t%.4f\n", yz.mz, 100.0 * yz.intensity / maxIntensity);
            out.flush();
        }
        // delimit this dataset from the rest
        out.print("\n\n");
    }

    // close the .data
    out.close();

    // render outDATA to outPDF using gnuplot
    // 105.0 here means 105% for the y-range of a [0%:100%] plot. We want to leave some buffer space at
    // at the top, and hence we go a little outside of the 100% max range.
    /* We intend to plot the fragmentation pattern, and so do not expect to see fragments that are bigger than the
     * original selected molecule.  We truncate the x-range to the specified m/z but since that will make values close
     * to the max hard to see we add a buffer and truncate the plot in the x-range to m/z + 50.0. */
    new Gnuplotter().plot2DImpulsesWithLabels(outDATA, outPDF, plotID.toArray(new String[plotID.size()]),
            mz + 50.0, "mz", 105.0, "intensity (%)", fmt);
}