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.microsoft.azure.storage.queue.QueueEncryptionPolicy.java

/**
 * Return an encrypted base64 encoded message along with encryption related metadata given a plain text message.
 * /*w w  w  . j  av  a2  s  .  c  o m*/
 * @param inputMessage
 *            The input message in bytes.
 * @return The encrypted message that will be uploaded to the service.
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
String encryptMessage(byte[] inputMessage) throws StorageException {
    Utility.assertNotNull("inputMessage", inputMessage);

    if (this.keyWrapper == null) {
        throw new IllegalArgumentException(SR.KEY_MISSING);
    }

    CloudQueueEncryptedMessage encryptedMessage = new CloudQueueEncryptedMessage();
    EncryptionData encryptionData = new EncryptionData();
    encryptionData.setEncryptionAgent(new EncryptionAgent(Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1,
            EncryptionAlgorithm.AES_CBC_256));

    try {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);

        Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKey aesKey = keyGen.generateKey();
        myAes.init(Cipher.ENCRYPT_MODE, aesKey);

        // Wrap key
        Pair<byte[], String> encryptedKey = this.keyWrapper
                .wrapKeyAsync(aesKey.getEncoded(), null /* algorithm */).get();
        encryptionData.setWrappedContentKey(new WrappedContentKey(this.keyWrapper.getKid(),
                encryptedKey.getKey(), encryptedKey.getValue()));

        encryptedMessage.setEncryptedMessageContents(
                new String(Base64.encode(myAes.doFinal(inputMessage, 0, inputMessage.length))));

        encryptionData.setContentEncryptionIV(myAes.getIV());
        encryptedMessage.setEncryptionData(encryptionData);
        return encryptedMessage.serialize();
    } catch (Exception e) {
        throw StorageException.translateClientException(e);
    }
}

From source file:blusunrize.immersiveengineering.common.blocks.metal.TileEntityConnectorLV.java

private void notifyAvailableEnergy(int energyStored, @Nullable Set<AbstractConnection> outputs) {
    if (outputs == null)
        outputs = ImmersiveNetHandler.INSTANCE.getIndirectEnergyConnections(pos, world, true);
    for (AbstractConnection con : outputs) {
        IImmersiveConnectable end = ApiUtils.toIIC(con.end, world);
        if (con.cableType != null && end != null && end.allowEnergyToPass(null)) {
            Pair<Float, Consumer<Float>> e = getEnergyForConnection(con);
            end.addAvailableEnergy(e.getKey(), e.getValue());
        }/*from ww w.j  av a  2s . c om*/
    }
}

From source file:io.confluent.kafka.connect.source.io.processing.csv.CSVRecordProcessor.java

@Override
public void configure(SpoolDirectoryConfig config, InputStream inputStream, FileMetadata fileMetadata)
        throws IOException {
    this.config = config;

    if (log.isDebugEnabled()) {
        log.debug("Configuring CSVParser...");
    }//www .  ja  va2  s  .c om

    DateTypeParser timestampDateConverter = new DateTypeParser(this.config.parserTimestampTimezone(),
            this.config.parserTimestampDateFormats());
    this.parser.registerTypeParser(Timestamp.SCHEMA, timestampDateConverter);

    this.csvParser = this.config.createCSVParserBuilder().build();
    this.streamReader = new InputStreamReader(inputStream, this.config.charset());
    this.csvReader = this.config.createCSVReaderBuilder(this.streamReader, csvParser).build();

    String[] fieldNames;

    if (this.config.firstRowAsHeader()) {
        if (log.isDebugEnabled()) {
            log.debug("Reading the first line ");
        }
        fieldNames = this.csvReader.readNext();
        if (log.isDebugEnabled()) {
            log.debug("FieldMapping names for the file are {}", Joiner.on(", ").join(fieldNames));
        }
    } else {
        fieldNames = null;
    }

    if (this.config.schemaFromHeader()) {
        Preconditions.checkState(this.config.firstRowAsHeader(),
                "If the %s is set to true, then %s must be set to true as well.",
                SpoolDirectoryConfig.CSV_SCHEMA_FROM_HEADER_KEYS_CONF,
                SpoolDirectoryConfig.CSV_FIRST_ROW_AS_HEADER_CONF);

        SchemaConfig schemaConfig = new SchemaConfig();

        for (int i = 0; i < fieldNames.length; i++) {
            FieldConfig fieldConfig = FieldConfig.create(Schema.OPTIONAL_STRING_SCHEMA);
            fieldConfig.name = fieldNames[i];
            fieldConfig.index = i;
            schemaConfig.fields.add(fieldConfig);
        }
        schemaConfig.keys = this.config.schemaFromHeaderKeys();
        schemaConfig.name = this.config.schemaName();
        Preconditions.checkNotNull(schemaConfig.name,
                "%s must be configured when generating the schema from the header row.",
                SpoolDirectoryConfig.CSV_SCHEMA_NAME_CONF);
        Preconditions.checkState(!schemaConfig.name.isEmpty(),
                "%s must be configured when generating the schema from the header row.",
                SpoolDirectoryConfig.CSV_SCHEMA_NAME_CONF);
        this.schemaConfig = schemaConfig;
    } else {
        this.schemaConfig = this.config.schemaConfig();

        if (this.config.firstRowAsHeader()) {
            Map<String, FieldConfig> map = new LinkedHashMap<>();
            for (FieldConfig field : this.schemaConfig.fields) {
                String mapKey = this.config.caseSensitiveFieldNames() ? field.name : field.name.toLowerCase();
                Preconditions.checkState(!map.containsKey(mapKey),
                        "Schema already has a field with name '%s' defined.", field.name);
                map.put(mapKey, field);
            }

            int fieldIndex = 0;
            for (String fieldName : fieldNames) {
                String mapKey = this.config.caseSensitiveFieldNames() ? fieldName : fieldName.toLowerCase();
                FieldConfig field = map.get(mapKey);

                if (null == field) {
                    if (log.isDebugEnabled()) {
                        log.debug("FieldMapping '{}' was not found in schema. Skipping.", fieldName);
                    }
                    continue;
                }
                field.index = fieldIndex;
                fieldIndex++;
            }

        } else {
            if (log.isDebugEnabled()) {
                log.debug("Laying out fields in the order they are in the schema.");
            }

            for (int i = 0; i < this.schemaConfig.fields.size(); i++) {
                FieldConfig field = this.schemaConfig.fields.get(i);
                field.index = i;
                if (log.isDebugEnabled()) {
                    log.debug("FieldMapping {} index {}.", field.name, field.index);
                }
            }
        }

    }

    Pair<SchemaConfig.ParserConfig, SchemaConfig.ParserConfig> parserConfigs = this.schemaConfig
            .parserConfigs(this.config);

    this.keyParserConfig = parserConfigs.getKey();
    this.valueParserConfig = parserConfigs.getValue();

    this.fileMetadata = fileMetadata;
}

From source file:com.reprezen.swagedit.validation.Validator.java

protected Set<SwaggerError> checkDuplicateKeys(Node document) {
    HashMultimap<Pair<Node, String>, Node> acc = HashMultimap.<Pair<Node, String>, Node>create();

    collectDuplicates(document, acc);//from  w  w w  .  j a  v a 2 s  .c  o m

    Set<SwaggerError> errors = Sets.newHashSet();
    for (Pair<Node, String> key : acc.keys()) {
        Set<Node> duplicates = acc.get(key);

        if (duplicates.size() > 1) {
            for (Node duplicate : duplicates) {
                errors.add(createDuplicateError(key.getValue(), duplicate));
            }
        }
    }

    return errors;
}

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

public List<PregrowthWell> 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  w w  w .  ja  v a 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<PregrowthWell> results = new ArrayList<>();
    for (Pair<String, String> coords : sortedCoordinates) {
        String msid = msids.get(coords);
        if (msid == null || msid.isEmpty()) {
            continue;
        }
        String sourcePlate = parser.getCompositionTables().get("source_plate").get(coords);
        String sourceWell = parser.getCompositionTables().get("source_well").get(coords);
        String composition = parser.getCompositionTables().get("composition").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);
        PregrowthWell s = INSTANCE.insert(db, p.getId(), index.getLeft(), index.getRight(), sourcePlate,
                sourceWell, msid, composition, note, growth);

        results.add(s);
    }

    return results;
}

From source file:mase.app.soccer.ProgSoccerAgent.java

private List<Pair<SoccerAgent, Double>> sortByProximity(Collection<SoccerAgent> agents, Double2D target) {
    List<Pair<SoccerAgent, Double>> closer = new ArrayList<>();
    for (SoccerAgent a : agents) {
        closer.add(Pair.of(a, a.distanceTo(target)));
    }/*from ww  w  .j a  v  a2  s.c  o  m*/
    Collections.sort(closer, new Comparator<Pair<SoccerAgent, Double>>() {
        @Override
        public int compare(Pair<SoccerAgent, Double> o1, Pair<SoccerAgent, Double> o2) {
            return Double.compare(o1.getValue(), o2.getValue());
        }

    });
    return closer;
}

From source file:com.reprezen.swagedit.core.validation.Validator.java

protected Set<SwaggerError> checkDuplicateKeys(Node document) {
    Map<Pair<Node, String>, Set<Node>> acc = new HashMap<>();

    collectDuplicates(document, acc);//from  w  ww . j  av  a2  s . co m

    Set<SwaggerError> errors = new HashSet<>();
    for (Pair<Node, String> key : acc.keySet()) {
        Set<Node> duplicates = acc.get(key);

        if (duplicates.size() > 1) {
            for (Node duplicate : duplicates) {
                errors.add(createDuplicateError(key.getValue(), duplicate));
            }
        }
    }

    return errors;
}

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

public List<FeedingLCMSWell> insertFromPlateComposition(DB db, PlateCompositionParser parser, Plate p)
        throws SQLException, IOException {
    Map<String, String> plateProperties = parser.getPlateProperties();
    String msid = null, composition = null;
    if (!plateProperties.containsKey("msid") && plateProperties.containsKey("composition")) {
        throw new RuntimeException("ERROR: assumed plate properties 'msid' and 'composition' do not exist");
    }/*  w w w .j  av a  2  s .c  om*/
    msid = trimAndComplain(plateProperties.get("msid"));
    composition = trimAndComplain(plateProperties.get("composition"));

    // If a few well dones't have a concentration, it's not work keeping.
    Map<Pair<String, String>, String> concentrations = parser.getCompositionTables().get("concentration");
    List<Pair<String, String>> sortedCoordinates = new ArrayList<>(concentrations.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
        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<FeedingLCMSWell> results = new ArrayList<>();
    for (Pair<String, String> coords : sortedCoordinates) {
        String concentraitonStr = parser.getCompositionTables().get("concentration").get(coords);
        if (concentraitonStr == null || concentraitonStr.isEmpty()) {
            continue;
        }
        String extract = parser.getCompositionTables().get("extract").get(coords);
        String chemical = parser.getCompositionTables().get("chemical").get(coords);
        Double concentration = Double.parseDouble(concentraitonStr);
        String note = null;
        if (parser.getCompositionTables().get("note") != null) {
            note = parser.getCompositionTables().get("note").get(coords);
        }
        Pair<Integer, Integer> index = parser.getCoordinatesToIndices().get(coords);
        FeedingLCMSWell s = INSTANCE.insert(db, new FeedingLCMSWell(null, p.getId(), index.getLeft(),
                index.getRight(), msid, composition, extract, chemical, concentration, note));

        results.add(s);
    }

    return results;
}

From source file:candr.yoclip.DefaultParserHelpFactoryTest.java

@Test
public void testGetOptionPropertyDescriptions() {

    final ParserHelpFactory<PropertiesTestCase> testCase = new DefaultParserHelpFactory<PropertiesTestCase>();
    final ParserOptions<PropertiesTestCase> parserOptions = new ParserOptionsFactory<PropertiesTestCase>(
            PropertiesTestCase.class).create();

    ParserOption<PropertiesTestCase> optionParameter = parserOptions.get("D");
    List<Pair<String, String>> descriptions = testCase.getOptionPropertyDescriptions(optionParameter);

    assertThat("size", descriptions.size(), is(3));

    Pair<String, String> propertyHelp = descriptions.get(0);
    assertThat("property help 0 synopsis", propertyHelp.getKey(), is("one"));
    assertThat("property help 0 details", propertyHelp.getValue(),
            is(new StrBuilder().append("Property one.").append(Options.LINE_BREAK).append(Options.LINE_BREAK)
                    .append("Has explicit line breaks.").toString()));

    propertyHelp = descriptions.get(1);/*from   ww  w . j ava  2 s .co  m*/
    assertThat("property help 1 synopsis", propertyHelp.getKey(), is("two"));
    assertThat("property help 1 details", propertyHelp.getValue(), is("Details for property two."));

    propertyHelp = descriptions.get(2);
    assertThat("property help 2 synopsis", propertyHelp.getKey(), is("key"));
    assertThat("property help 2 details", propertyHelp.getValue(),
            is("An option property value for properties."));
}

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 {//  ww  w  .ja v 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.");

    }
}