Example usage for org.apache.commons.lang3.tuple ImmutablePair of

List of usage examples for org.apache.commons.lang3.tuple ImmutablePair of

Introduction

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

Prototype

public static <L, R> ImmutablePair<L, R> of(final L left, final R right) 

Source Link

Document

Obtains an immutable pair of from two objects inferring the generic types.

This factory allows the pair to be created using inference to obtain the generic types.

Usage

From source file:com.offbynull.voip.kademlia.model.KBucket.java

private ImmutablePair<Activity, Activity> replaceNextStaleNodeWithCacheNode() {
    if (staleSet.isEmpty()) {
        return null;
    }//from  www. j  av a 2  s  .  com

    // Get stale node
    Iterator<Id> staleIt = staleSet.iterator();
    Id staleId = staleIt.next();

    // Check to make sure cache has items to replace with
    if (cache.size() == 0) {
        return null;
    }

    // Remove from bucket and staleset
    staleIt.remove(); // remove from staleset
    Node staleNode = bucket.get(staleId);
    ActivityChangeSet bucketRemoveRes = bucket.remove(staleNode); // throws EntryConflictException if id is equal but link isn't
    if (bucketRemoveRes.viewRemoved().isEmpty()) {
        return null;
    }

    // Remove latest from cache and add to bucket
    ActivityChangeSet cacheRemoveRes = cache.removeMostRecent(1);
    ActivityChangeSet bucketTouchRes;
    Validate.validState(cacheRemoveRes.viewRemoved().size() == 1); // sanity check, should always remove 1 node
    Activity cacheEntry = cacheRemoveRes.viewRemoved().get(0);
    try {
        bucketTouchRes = bucket.touch(cacheEntry.getTime(), cacheEntry.getNode(), false);
    } catch (LinkMismatchException ece) {
        // should never throw EntryConflictException
        throw new IllegalStateException(ece);
    }
    Validate.validState(bucketTouchRes.viewAdded().size() == 1); // sanity check, should always add 1 node

    return ImmutablePair.of(bucketRemoveRes.viewRemoved().get(0), bucketTouchRes.viewAdded().get(0));
}

From source file:cc.kave.commons.pointsto.analysis.unification.UnificationAnalysisVisitorContext.java

public void enterLambda(ILambdaExpression lambdaExpr) {
    ReferenceLocation lambdaReturnLocation = createSimpleReferenceLocation();
    lambdaStack.addFirst(ImmutablePair.of(lambdaExpr, lambdaReturnLocation));
}

From source file:edu.ksu.cis.santos.mdcf.dml.symbol.SymbolTable.java

/**
 * Retrieves an immutable map {@link Map} whose entries come from the provided
 * map where the entries' value's second element is an instance of the
 * provided {@link Class}.//from  w  w  w .  ja v  a2 s  . c  o m
 * 
 * @param m
 *          The map whose entries will be used to construct a filtered map
 *          according to the provided class.
 * @param clazz
 *          The class for filtering the provided map.
 * @return an immutable {@link Map}.
 */
public <V, T> Map<String, Pair<Feature, T>> filterp(final Map<String, Pair<Feature, V>> m,
        final Class<T> clazz) {
    return Maps.transformValues(Maps.filterValues(m, new Predicate<Pair<Feature, V>>() {
        @Override
        public boolean apply(@Nullable final Pair<Feature, V> input) {
            if (input != null) {
                return clazz.isAssignableFrom(input.getRight().getClass());
            } else {
                return false;
            }
        }
    }), new Function<Pair<Feature, V>, Pair<Feature, T>>() {
        @SuppressWarnings("unchecked")
        @Override
        @Nullable
        public Pair<Feature, T> apply(@Nullable final Pair<Feature, V> input) {
            return ImmutablePair.of(input.getLeft(), (T) input.getRight());
        }
    });
}

From source file:com.joyent.manta.client.multipart.ServerSideMultipartManager.java

/**
 * Creates the JSON request body used to commit all of the parts of a multipart
 * upload request./*from  w w w.  ja  va  2  s  .  co m*/
 *
 * @param parts stream of tuples - this is a terminal operation that will close the stream
 * @return byte array containing JSON data
 */
static ImmutablePair<byte[], Integer> createCommitRequestBody(
        final Stream<? extends MantaMultipartUploadTuple> parts) {
    final JsonNodeFactory nodeFactory = MantaObjectMapper.NODE_FACTORY_INSTANCE;
    final ObjectNode objectNode = new ObjectNode(nodeFactory);

    final ArrayNode partsArrayNode = new ArrayNode(nodeFactory);
    objectNode.set("parts", partsArrayNode);

    try (Stream<? extends MantaMultipartUploadTuple> sorted = parts.sorted()) {
        sorted.forEach(tuple -> partsArrayNode.add(tuple.getEtag()));
    }

    Validate.isTrue(partsArrayNode.size() > 0, "Can't commit multipart upload with no parts");

    try {
        return ImmutablePair.of(MantaObjectMapper.INSTANCE.writeValueAsBytes(objectNode),
                partsArrayNode.size());
    } catch (IOException e) {
        String msg = "Error serializing JSON for commit MPU request body";
        throw new MantaMultipartException(msg, e);
    }
}

From source file:candr.yoclip.Parser.java

protected String createHelp() {

    final ParserOptions<T> parserOptions = getParserOptions();
    final ParserHelpFactory<T> parserHelpFactory = getParserHelpFactory();

    final StrBuilder builder = new StrBuilder();

    // the usage synopsis is first
    builder.append("Usage: ").append(parserOptions.getName()).append(' ').appendln(getUsage());

    // followed by the header if one is available
    final String header = parserHelpFactory.getHeaderDescription(parserOptions);
    if (!StringUtils.isEmpty(header)) {

        if (isSpaceBeforeHeader()) {
            builder.appendNewLine();/*from   w  w  w  . j  a  v a  2 s .c  o  m*/
        }

        builder.appendln(parserHelpFactory.wrap(header, getWidth()));
    }

    // followed by the option descriptions
    final String prefix = parserOptions.getPrefix();
    final String separator = parserOptions.getSeparator();

    // get all the options descriptions
    int hangingIndentSize = 0;
    final List<Pair<Boolean, Pair<String, String>>> optionDescriptionWrappers = new LinkedList<Pair<Boolean, Pair<String, String>>>();
    for (final ParserOption<T> parserOption : parserOptions.get()) {

        final Pair<String, String> optionDescription = parserHelpFactory.getOptionDescription(prefix, separator,
                parserOption);
        optionDescriptionWrappers.add(ImmutablePair.of(true, optionDescription));
        hangingIndentSize = Math.max(hangingIndentSize, optionDescription.getLeft().length());

        for (final Pair<String, String> optionPropertyDescription : parserHelpFactory
                .getOptionPropertyDescriptions(parserOption)) {
            optionDescriptionWrappers.add(ImmutablePair.of(false, optionPropertyDescription));
        }
    }

    // now add the help to the builder
    int maxIndentSize = getWidth() / 4;
    hangingIndentSize = Math.min(hangingIndentSize + 2, maxIndentSize);
    for (final Pair<Boolean, Pair<String, String>> optionDescriptionWrapper : optionDescriptionWrappers) {

        if (isSpaceBetweenOptionDescriptions()) {
            builder.appendNewLine();
        }

        // create the option description or option property description
        final StrBuilder descriptionBuilder = new StrBuilder();
        if (optionDescriptionWrapper.getLeft()) {

            final Pair<String, String> optionDescription = optionDescriptionWrapper.getRight();
            descriptionBuilder.append(StringUtils.rightPad(optionDescription.getLeft(), hangingIndentSize));
            if (descriptionBuilder.length() > hangingIndentSize) {
                descriptionBuilder.append(" ");
            }
            descriptionBuilder.append(optionDescription.getRight());

        } else {

            final Pair<String, String> optionPropertyDescription = optionDescriptionWrapper.getRight();
            descriptionBuilder.appendPadding(hangingIndentSize, ' ').append("'")
                    .append(optionPropertyDescription.getLeft()).append("' ")
                    .append(optionPropertyDescription.getRight());
        }
        builder.appendln(parserHelpFactory.hangingIndentWrap(descriptionBuilder.toString(), hangingIndentSize,
                getWidth()));
    }

    // followed by the trailer if one is available
    final String trailer = parserHelpFactory.getTrailerDescription(parserOptions);
    if (!StringUtils.isEmpty(trailer)) {

        if (isSpaceBeforeTrailer()) {
            builder.appendNewLine();
        }

        builder.appendln(parserHelpFactory.wrap(trailer, getWidth()));
    }

    return builder.toString();
}

From source file:com.shieldsbetter.sbomg.ViewModelGenerator.java

private static void outfitModel(ModelClass dest, String contextName, Set<String> options, Object modelDesc) {
    boolean finalFlag = options.contains("final");
    boolean leafFlag = options.contains("leaf");

    String fieldName = contextName;
    if (fieldName.isEmpty()) {
        fieldName = "Value";
    }/*from   w  ww .j a  va2  s . c o  m*/

    if (modelDesc instanceof String) {
        String fieldTypeString = (String) modelDesc;
        TypeName fieldType = typeName(fieldTypeString);

        FieldSpec.Builder fieldBuild = FieldSpec.builder(fieldType, "my" + fieldName, Modifier.PRIVATE);

        dest.addRootMethod("get" + fieldName, fieldType, ImmutableList.of(),
                CodeBlock.builder().addStatement("return my$L", fieldName).build());

        if (!leafFlag) {
            dest.addListenerEvent(contextName + "Updated",
                    ImmutableList.of(ImmutablePair.of("value", fieldType),
                            ImmutablePair.of("event", ClassName.get("", fieldTypeString + ".Event"))));
        }

        if (finalFlag) {
            fieldBuild.addModifiers(Modifier.FINAL);

            String paramName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, fieldName);
            dest.addInitializationParameter(paramName, fieldType);
            dest.addInitializationCode(
                    CodeBlock.builder().addStatement("my$L = $L", fieldName, paramName).build());

            if (!leafFlag) {
                dest.addInitializationCode(renderCodeBlock(SUBSCRIBE_TEMPL, "finalFlag", finalFlag, "fieldName",
                        fieldName, "fieldType", fieldTypeString, "parentType", dest.getName()));
            }
        } else {
            String subscribeCode;
            if (leafFlag) {
                subscribeCode = "";
            } else {
                FieldSpec.Builder subscriptionField = FieldSpec.builder(
                        ClassName.get("", fieldTypeString + ".Subscription"), "my" + fieldName + "Subscription",
                        Modifier.PRIVATE);
                dest.addField(subscriptionField.build());

                subscribeCode = renderTemplate(SUBSCRIBE_TEMPL, "finalFlag", finalFlag, "fieldName", fieldName,
                        "fieldType", fieldTypeString, "parentType", dest.getName());
            }

            dest.addBuildCode(
                    CodeBlock.builder().addStatement("l.on$LSet(this, my$L)", contextName, fieldName).build());

            dest.addListenerEvent(contextName + "Set",
                    ImmutableList.of(ImmutablePair.of("newValue", fieldType)));

            dest.addRootMethod("set" + contextName, TypeName.VOID,
                    ImmutableList.of(ImmutablePair.of("newValue", fieldType)),
                    renderCodeBlock(SET_METHOD_TEMPL, "parentType", dest.getName(), "fieldName", fieldName,
                            "valueParam", "newValue", "leafFlag", leafFlag, "contextName", contextName,
                            "afterUnsubscribe", subscribeCode));
        }

        dest.addField(fieldBuild.build());
    } else if (modelDesc instanceof List) {
        List listDesc = (List) modelDesc;

        switch (listDesc.size()) {
        case 1: {
            outfitModelWithList(dest, contextName, options, listDesc.get(0));
            break;
        }
        case 2: {
            outfitModelWithList(dest, contextName, options, listDesc);
            break;
        }
        default: {
            throw new RuntimeException();
        }
        }
    } else if (modelDesc instanceof Map) {
        Map<String, Object> mapDesc = (Map<String, Object>) modelDesc;
        for (Map.Entry<String, Object> field : mapDesc.entrySet()) {
            outfitModel(dest, contextName + field.getKey(), field.getValue());
        }
    } else {
        throw new RuntimeException(modelDesc.getClass().getSimpleName());
    }
}

From source file:com.joyent.manta.client.crypto.AbstractMantaEncryptedObjectInputStreamTest.java

/**
 *
 * Builds an {@link InputStream} from the supplied file and returns it. In case a failure percentage and order are
 * provided, we will://from ww  w . j a v a  2 s.c o  m
 *  - wrap the first stream in a {@link FailingInputStream}
 *  - build an {@link InputStreamContinuator} which can provide streams for the remaining data
 *  - build an {@link AutoContinuingInputStream} which uses the continuator to recover from the initial failure
 *
 * We need to return both the requested {@link InputStream} and (if on exists) the {@link InputStreamContinuator}
 * so that the test can check that the continuator was actually used.
 */
//@formatter:on
private static Pair<InputStream, InputStreamContinuator> buildEncryptedFileInputStream(
        final EncryptedFile encryptedFile, final Integer failureOffset, final FailureOrder failureOrder)
        throws FileNotFoundException {
    if (failureOffset == null ^ failureOrder == null) {
        throw new AssertionError("One of failure offset or order provided but the other was null, "
                + "this is most likely a mistake. "
                + "If you're passing ON_EOF, supply any integer for the offset");
    }

    if (failureOffset == null || failureOrder == null) {
        return ImmutablePair.of(new FileInputStream(encryptedFile.file), null);
    }

    final InputStream initialStream = new FailingInputStream(new FileInputStream(encryptedFile.file),
            failureOrder, failureOffset);
    final InputStreamContinuator continuator = Mockito.spy(new FileInputStreamContinuator(encryptedFile.file));

    return ImmutablePair.of(new AutoContinuingInputStream(initialStream, continuator), continuator);
}

From source file:candr.yoclip.ParserTest.java

@Test
public void createHelp() {

    final ParserOption<ParserTest> mockOption = createMockOption("o");
    final ParserOption<ParserTest> mockOptionProperty = createMockOptionProperty("P");
    final ParserOption<ParserTest> mockArguments = createMockArguments();

    final String prefix = "-";
    final String separator = "=";
    final ParserOptions<ParserTest> mockParserOptions = createMockParserParameters(prefix, separator);
    when(mockParserOptions.getName()).thenReturn("testCase");
    when(mockParserOptions.get()).thenReturn(Arrays.asList(mockOption, mockOptionProperty, mockArguments));
    when(mockParserOptions.get("o")).thenReturn(mockOption);
    when(mockParserOptions.get("P")).thenReturn(mockOptionProperty);
    when(mockParserOptions.get(ParserOptions.ARGUMENTS_KEY)).thenReturn(mockArguments);
    when(mockParserOptions.getArguments()).thenReturn(mockArguments);

    final ParserHelpFactory<ParserTest> mockParserHelpFactory = createMockParserHelpFactory();

    final String header = "header";
    when(mockParserHelpFactory.getHeaderDescription(mockParserOptions)).thenReturn(header);
    when(mockParserHelpFactory.wrap(header, Parser.MINIMUM_WIDTH)).thenReturn("wrapped header");

    final String trailer = "trailer";
    when(mockParserHelpFactory.getTrailerDescription(mockParserOptions)).thenReturn(trailer);
    when(mockParserHelpFactory.wrap(trailer, Parser.MINIMUM_WIDTH)).thenReturn("wrapped trailer");

    final Pair<String, String> oneDescription = ImmutablePair.of("one", "one description");
    when(mockParserHelpFactory.getOptionDescription(prefix, separator, mockOption)).thenReturn(oneDescription);
    when(mockParserHelpFactory.hangingIndentWrap("one   one description", 6, Parser.MINIMUM_WIDTH))
            .thenReturn("option");

    final Pair<String, String> twoDescription = ImmutablePair.of("two", "two description");
    when(mockParserHelpFactory.getOptionDescription(prefix, separator, mockOptionProperty))
            .thenReturn(twoDescription);
    when(mockParserHelpFactory.hangingIndentWrap("two   two description", 6, Parser.MINIMUM_WIDTH))
            .thenReturn("property");
    when(mockParserHelpFactory.getOptionPropertyDescriptions(mockOptionProperty)).thenReturn(
            Arrays.asList(Pair.of("prop1", "prop1 description"), Pair.of("prop2", "prop2 description")));
    when(mockParserHelpFactory.hangingIndentWrap("      'prop1' prop1 description", 6, Parser.MINIMUM_WIDTH))
            .thenReturn("  prop1");
    when(mockParserHelpFactory.hangingIndentWrap("      'prop2' prop2 description", 6, Parser.MINIMUM_WIDTH))
            .thenReturn("  prop2");

    final Pair<String, String> threeDescription = ImmutablePair.of("argument", "three description");
    when(mockParserHelpFactory.getOptionDescription(prefix, separator, mockArguments))
            .thenReturn(threeDescription);
    when(mockParserHelpFactory.hangingIndentWrap("argument three description", 6, Parser.MINIMUM_WIDTH))
            .thenReturn("argument");

    final String expectedFullHelp = new StrBuilder().appendln("Usage: testCase unit test").appendNewLine()
            .appendln("wrapped header").appendNewLine().appendln("option").appendNewLine().appendln("property")
            .appendNewLine().appendln("  prop1").appendNewLine().appendln("  prop2").appendNewLine()
            .appendln("argument").appendNewLine().appendln("wrapped trailer").toString();
    final Parser<ParserTest> testCase = new Parser<ParserTest>(mockParserOptions, mockParserHelpFactory);
    testCase.setUsage("unit test");
    testCase.setWidth(Parser.MINIMUM_WIDTH);

    String help = testCase.createHelp();
    assertThat("full help", help, is(expectedFullHelp));

}

From source file:gobblin.data.management.conversion.hive.converter.AbstractAvroToOrcConverter.java

private Pair<Optional<Table>, Optional<List<Partition>>> getDestinationTableMeta(String dbName,
        String tableName, WorkUnitState state) throws DataConversionException {

    Optional<Table> table = Optional.<Table>absent();
    Optional<List<Partition>> partitions = Optional.<List<Partition>>absent();

    try {// ww  w  . j ava  2 s  .c om
        HiveMetastoreClientPool pool = HiveMetastoreClientPool.get(state.getJobState().getProperties(),
                Optional.fromNullable(state.getJobState().getProp(HiveDatasetFinder.HIVE_METASTORE_URI_KEY)));
        try (AutoReturnableObject<IMetaStoreClient> client = pool.getClient()) {
            table = Optional.of(client.get().getTable(dbName, tableName));
            if (table.isPresent()) {
                org.apache.hadoop.hive.ql.metadata.Table qlTable = new org.apache.hadoop.hive.ql.metadata.Table(
                        table.get());
                if (HiveUtils.isPartitioned(qlTable)) {
                    partitions = Optional
                            .of(HiveUtils.getPartitions(client.get(), qlTable, Optional.<String>absent()));
                }
            }
        }
    } catch (NoSuchObjectException e) {
        return ImmutablePair.of(table, partitions);
    } catch (IOException | TException e) {
        throw new DataConversionException("Could not fetch destination table metadata", e);
    }

    return ImmutablePair.of(table, partitions);
}

From source file:gobblin.data.management.conversion.hive.validation.ValidationJob.java

private Pair<Optional<org.apache.hadoop.hive.metastore.api.Table>, Optional<List<Partition>>> getDestinationTableMeta(
        String dbName, String tableName, Properties props) {

    Optional<org.apache.hadoop.hive.metastore.api.Table> table = Optional.absent();
    Optional<List<Partition>> partitions = Optional.absent();

    try {//from w w  w  . ja v a2s  .  com
        try (AutoReturnableObject<IMetaStoreClient> client = pool.getClient()) {
            table = Optional.of(client.get().getTable(dbName, tableName));
            if (table.isPresent()) {
                org.apache.hadoop.hive.ql.metadata.Table qlTable = new org.apache.hadoop.hive.ql.metadata.Table(
                        table.get());
                if (HiveUtils.isPartitioned(qlTable)) {
                    partitions = Optional
                            .of(HiveUtils.getPartitions(client.get(), qlTable, Optional.<String>absent()));
                }
            }
        }
    } catch (NoSuchObjectException e) {
        return ImmutablePair.of(table, partitions);
    } catch (IOException | TException e) {
        throw new RuntimeException("Could not fetch destination table metadata", e);
    }

    return ImmutablePair.of(table, partitions);
}