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

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

Introduction

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

Prototype

public ImmutablePair(final L left, final R right) 

Source Link

Document

Create a new pair instance.

Usage

From source file:com.netflix.spinnaker.halyard.deploy.provider.v1.kubernetes.KubernetesProviderInterface.java

private Pair<VolumeMount, Volume> buildVolumePair(String secretName, String dirName) {
    VolumeMountBuilder volumeMountBuilder = new VolumeMountBuilder();
    volumeMountBuilder.withName(secretName).withMountPath(dirName);

    VolumeBuilder volumeBuilder = new VolumeBuilder().withNewSecret().withSecretName(secretName).endSecret()
            .withName(secretName);// w  w w  . j ava  2 s.  co  m

    return new ImmutablePair<>(volumeMountBuilder.build(), volumeBuilder.build());
}

From source file:com.github.aptd.simulation.datamodel.CXMLReader.java

/**
 * get an agent-reference name/* www  . j  ava 2s. c  o  m*/
 *
 * @param p_value value of the agent-reference
 * @param p_list object list
 * @return agent-reference name
 * @throws CNotFoundException is thrown on not found
 */
@SuppressWarnings("unchecked")
private static <T> Pair<T, String> agentname(final T p_value, final List<Object> p_list) {
    return new ImmutablePair<T, String>(p_value,
            p_list.parallelStream().filter(a -> a instanceof AgentRef).findAny().map(a -> (AgentRef) a)
                    .map(AgentRef::getAgent).orElseThrow(() -> new CNotFoundException(
                            CCommon.languagestring(CXMLReader.class, "agentreferencenotfound"))));
}

From source file:be.shad.tsqb.test.SelectTests.java

/**
 * Select an object and use some of the values of this object to transform into another dto.
 * <p>/*from   ww w  .  j a va2  s  . c o m*/
 * Using a proxy as select value to get values from it should be avoided. Only do this
 * if there is no other option! (value on a dto without a default constructor for example)
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void selectProxyTransformedValue() {
    Person person = query.from(Person.class);
    Relation relation = query.join(person.getChildRelations());

    MutablePair<Long, ImmutablePair<Long, Integer>> select = query.select(MutablePair.class);
    select.setLeft(person.getId());
    select.setRight(query.select(ImmutablePair.class, relation.getChild(),
            new SelectionValueTransformer<Person, ImmutablePair>() {
                @Override
                public ImmutablePair<Long, Integer> convert(Person a) {
                    return new ImmutablePair<Long, Integer>(a.getId(), a.getAge());
                }
            }));

    validate(
            "select hobj1.id as left, hobj3 as right from Person hobj1 join hobj1.childRelations hobj2 join hobj2.child hobj3");
}

From source file:com.intuit.wasabi.assignment.impl.AssignmentsImpl.java

/**
 * Create/Retrieve assignments for a given user, application, context and
 * given experiments (experimentBatch/allowAssignments).
 * <p>/*from w  w  w .  j a  v a  2 s .co m*/
 * <p>
 * This method is called from:
 * 1. First directly through API call AssignmentsImpl.doBatchAssignments() => api:/v1/assignments/applications/{applicationName}/users/{userID}
 * In this case pageName and allowAssignments are NULL
 * And ExperimentBatch is provided with experiment labels
 * <p>
 * 2. Second from AssignmentsImpl.doPageAssignments() => api:/v1/assignments/applications/{applicationName}/pages/{pageName}/users/{userID}
 * In this case pageName and allowAssignments are provided.
 * And ExperimentBatch is empty
 * <p>
 * 3. Third from  AssignmentsImpl.doSingleAssignment() => api:/v1/assignments/applications/{applicationName}/experiments/{experiment}/users/{userID}
 * In this case pageName and allowAssignments are NULL
 * And ExperimentBatch is provided with a single experiment label
 * <p>
 * 4. Forth from  AssignmentsImpl.getExistingAssignment() => api:/v1/events/applications/{applicationName}/experiments/{experimentLabel}/users/{userID}
 * In this case pageName and allowAssignments are NULL
 * And ExperimentBatch is provided with a single experiment label
 *
 * @param userID                  the {@link com.intuit.wasabi.assignmentobjects.User.ID} of the person we want the assignment for
 * @param applicationName         the {@link com.intuit.wasabi.experimentobjects.Application.Name} the app we want the assignment for
 * @param context                 the {@link Context} of the assignment call
 * @param createAssignment        <code>true</code> when a new Assignment should be created
 * @param forceInExperiment
 * @param headers                 the {@link HttpHeaders} that can be used by the segmentation
 * @param experimentBatch         the {@link ExperimentBatch} experiment batch for batch assignments
 *                                Experiment labels are NOT PRESENT when called from AssignmentsImpl.doPageAssignments()
 * @param pageName                the {@link com.intuit.wasabi.experimentobjects.Page.Name} the page name for the assignment
 *                                NULL when called from AssignmentsResource.getBatchAssignments()
 *                                PRESENT when called from AssignmentsImpl.doPageAssignments()
 * @param allowAssignments        {@link HashMap} for each experiment whether the assignment is allowed
 *                                NULL when called from AssignmentsResource.getBatchAssignments()
 *                                PRESENT when called from AssignmentsImpl.doPageAssignments()
 * @param updateDownstreamSystems if TRUE then only send assignments events to the downstream systems.
 * @return List of assignment objects
 */
protected List<Assignment> doAssignments(User.ID userID, Application.Name applicationName, Context context,
        boolean createAssignment, boolean forceInExperiment, HttpHeaders headers,
        ExperimentBatch experimentBatch, Page.Name pageName, Map<Experiment.ID, Boolean> allowAssignments,
        boolean updateDownstreamSystems) {

    //allowAssignments is NULL when called from AssignmentsResource.getBatchAssignments()
    Optional<Map<Experiment.ID, Boolean>> allowAssignmentsOptional = Optional.ofNullable(allowAssignments);
    PrioritizedExperimentList appPriorities = new PrioritizedExperimentList();
    Map<Experiment.ID, com.intuit.wasabi.experimentobjects.Experiment> experimentMap = new HashMap<>();
    Table<Experiment.ID, Experiment.Label, String> userAssignments = HashBasedTable.create();
    Map<Experiment.ID, BucketList> bucketMap = new HashMap<>();
    Map<Experiment.ID, List<Experiment.ID>> exclusionMap = new HashMap<>();

    //Populate required assignment metadata
    populateAssignmentsMetadata(userID, applicationName, context, experimentBatch, allowAssignmentsOptional,
            appPriorities, experimentMap, bucketMap, exclusionMap);

    //Now fetch existing user assignments for given user, application & context
    assignmentsRepository.getAssignments(userID, applicationName, context, experimentMap)
            .forEach(assignmentPair -> userAssignments.put(assignmentPair.getLeft().getID(),
                    assignmentPair.getLeft().getLabel(), assignmentPair.getRight().toString()));
    LOGGER.debug("[DB] existingUserAssignments = {}", userAssignments);

    List<Pair<Experiment, Assignment>> assignmentPairs = new LinkedList<>();
    List<Assignment> allAssignments = new LinkedList<>();
    SegmentationProfile segmentationProfile = SegmentationProfile.from(experimentBatch.getProfile()).build();

    // iterate over all experiments in the application in priority order
    for (PrioritizedExperiment experiment : appPriorities.getPrioritizedExperiments()) {
        LOGGER.debug("Now processing: {}", experiment);

        //check if the experiment was given in experimentBatch
        if (experimentBatch.getLabels().contains(experiment.getLabel())) {
            LOGGER.debug("Experiment ({}) is part of given ExperimentBatch....", experiment.getLabel());

            String labelStr = experiment.getLabel().toString();
            Experiment.Label label = Experiment.Label.valueOf(labelStr);
            Assignment assignment = null;
            try {
                boolean experimentCreateAssignment = allowAssignmentsOptional.isPresent()
                        ? (allowAssignmentsOptional.get().get(experiment.getID()))
                        : createAssignment;

                //This method only gets assignment object, and doesn't create new assignments in a database (cassandra)
                assignment = getAssignment(userID, applicationName, label, context, experimentCreateAssignment,
                        forceInExperiment, segmentationProfile, headers, experimentMap.get(experiment.getID()),
                        bucketMap.get(experiment.getID()), userAssignments, exclusionMap);

                // This wouldn't normally happen because we specified CREATE=true
                if (isNull(assignment)) {
                    continue;
                }

                // Add the assignment to the global list of userAssignments of the user
                if (assignment.getStatus() != Assignment.Status.EXPERIMENT_EXPIRED) {
                    userAssignments.put(experiment.getID(), experiment.getLabel(),
                            assignment.getBucketLabel() != null ? assignment.getBucketLabel().toString()
                                    : "null");
                }

                assignmentPairs.add(new ImmutablePair<Experiment, Assignment>(
                        experimentMap.get(experiment.getID()), assignment));

            } catch (WasabiException ex) {
                LOGGER.error("Exception happened while executing assignment business logic", ex);
                assignment = nullAssignment(userID, applicationName, experiment.getID(), label,
                        ASSIGNMENT_FAILED);
            }

            allAssignments.add(assignment);
            experimentBatch.getLabels().remove(experiment.getLabel());
        } else {
            LOGGER.debug("Experiment ({}) is NOT part of given ExperimentBatch....", experiment.getLabel());
        }
    }

    //Find if there are any experiment which is not part of application-experiment list
    List<Experiment.Label> pExpLables = appPriorities.getPrioritizedExperiments().stream()
            .map(pExp -> pExp.getLabel()).collect(Collectors.toList());
    experimentBatch.getLabels().forEach(iExpLabel -> {
        if (!pExpLables.contains(iExpLabel)) {
            allAssignments
                    .add(nullAssignment(userID, applicationName, null, Assignment.Status.EXPERIMENT_NOT_FOUND));
        }
    });

    LOGGER.debug("Finished Execute_Assignments_BL, AllAssignments: {} ", allAssignments);

    //Make new assignments in database (cassandra)
    final Date currentDate = new Date();
    Stream<Pair<Experiment, Assignment>> newAssignments = assignmentPairs.stream().filter(pair -> {
        return (nonNull(pair) && pair.getRight().getStatus() == Assignment.Status.NEW_ASSIGNMENT);
    });
    assignmentsRepository.assignUsersInBatch(newAssignments.collect(Collectors.toList()), currentDate);
    LOGGER.debug("Finished Create_Assignments_DB...");

    //Ingest data to real time data ingestion systems if executors exist & if asked to update downstream systems
    if (updateDownstreamSystems) {
        assignmentPairs.forEach(assignmentPair -> {
            Assignment assignment = assignmentPair.getRight();
            Experiment experiment = assignmentPair.getLeft();
            boolean experimentCreateAssignment = allowAssignmentsOptional.isPresent()
                    ? (allowAssignmentsOptional.get().get(experiment.getID()))
                    : createAssignment;
            for (String name : executors.keySet()) {
                executors.get(name).execute(new AssignmentEnvelopePayload(userID, context,
                        experimentCreateAssignment, false, forceInExperiment, segmentationProfile,
                        assignment != null ? assignment.getStatus() : null,
                        assignment != null ? assignment.getBucketLabel() : null, pageName, applicationName,
                        experiment.getLabel(), experiment.getID(), currentDate, headers));
            }
        });
        LOGGER.debug("Finished Ingest_to_downstream_systems...");
    }

    // Updating rule cache, This will cause future assignment calls, on this server, to
    // use the new version of the rule, if it has recently been changed.
    assignmentPairs.forEach(assignmentPair -> {
        Experiment experiment = assignmentPair.getLeft();
        ruleCacheExecutor.execute(
                new ExperimentRuleCacheUpdateEnvelope(experiment.getRule(), ruleCache, experiment.getID()));
    });
    LOGGER.debug("Finished update_rule_cache...");

    return allAssignments;
}

From source file:io.pravega.controller.store.stream.AbstractStreamMetadataStore.java

protected Stream getStream(String scope, final String name, OperationContext context) {
    Stream stream;//from  w  w w  . j  a  va  2  s.  co  m
    if (context != null) {
        stream = context.getStream();
        assert stream.getScope().equals(scope);
        assert stream.getName().equals(name);
    } else {
        stream = cache.getUnchecked(new ImmutablePair<>(scope, name));
        stream.refresh();
    }
    return stream;
}

From source file:com.epam.ngb.cli.manager.command.handler.http.AbstractHTTPCommandHandler.java

/**
 * Method splits path for file registartion into file-index pair
 * @param path input CLI argument/*  ww w . ja v  a  2  s  .  co  m*/
 * @return pair, where left part is path to file and rights one optional path to index
 */
protected Pair<String, String> parseAndVerifyFilePath(String path) {
    Pair<String, String> fileWithIndex = splitFilePath(path);
    BiologicalDataItemFormat format = BiologicalDataItemFormat.getByFilePath(fileWithIndex.getLeft());
    if (format.isRequireIndex() && fileWithIndex.getRight() == null) {
        throw new IllegalArgumentException(getMessage(ERROR_INDEX_REQUIRED, fileWithIndex.getLeft()));
    }
    if (fileWithIndex.getRight() != null) {
        boolean indexSupported = format.verifyIndex(fileWithIndex.getRight());
        //if server doesn't support a given index, but index is also not required
        //we don't pass it to server
        if (!indexSupported) {
            return new ImmutablePair<>(fileWithIndex.getLeft(), null);
        }
    }
    return fileWithIndex;
}

From source file:edu.kit.trufflehog.view.jung.visualization.FXVisualizationViewer.java

private void onSelectionChanged() {

    final IUserCommand selectionCommand = interactionMap.get(GraphInteraction.SELECTION);

    if (selectionCommand == null) {
        logger.warn("There is no command registered to: " + GraphInteraction.SELECTION);
        return;//w  w w  .  ja  va2s .  c o m
    }

    selectionCommand.setSelection(new ImmutablePair<>(new HashSet<>(selectionModel.getSelectedVertices()),
            new HashSet<>(selectionModel.getSelectedEdges())));

    notifyListeners(selectionCommand);

}

From source file:co.rsk.peg.BridgeSupport.java

private void processSigning(long executionBlockNumber, BtcECKey federatorPublicKey, List<byte[]> signatures,
        byte[] rskTxHash, BtcTransaction btcTx) throws IOException {
    int i = 0;/*w  w  w . ja v a 2 s. c o m*/
    for (TransactionInput txIn : btcTx.getInputs()) {
        Script inputScript = txIn.getScriptSig();
        List<ScriptChunk> chunks = inputScript.getChunks();
        byte[] program = chunks.get(chunks.size() - 1).data;
        Script redeemScript = new Script(program);
        Sha256Hash sighash = btcTx.hashForSignature(i, redeemScript, BtcTransaction.SigHash.ALL, false);
        BtcECKey.ECDSASignature sig = BtcECKey.ECDSASignature.decodeFromDER(signatures.get(i));

        if (!federatorPublicKey.verify(sighash, sig)) {
            logger.warn("Signature {} {} is not valid for hash {} and public key {}", i,
                    Hex.toHexString(sig.encodeToDER()), sighash, federatorPublicKey);
            return;
        }
        TransactionSignature txSig = new TransactionSignature(sig, BtcTransaction.SigHash.ALL, false);
        if (!txSig.isCanonical()) {
            logger.warn("Signature {} is not canonical.", Hex.toHexString(signatures.get(i)));
            return;
        }

        boolean alreadySignedByThisFederator = isSignatureSignedByThisFederator(federatorPublicKey, sighash,
                inputScript.getChunks());

        if (!alreadySignedByThisFederator) {
            int sigIndex = inputScript.getSigInsertionIndex(sighash, federatorPublicKey);
            inputScript = ScriptBuilder.updateScriptWithSignature(inputScript, txSig.encodeToBitcoin(),
                    sigIndex, 1, 1);
            txIn.setScriptSig(inputScript);
            logger.debug("Tx input for tx {} signed.", new Sha3Hash(rskTxHash));
        } else {
            logger.warn("Tx {} already signed by this federator.", new Sha3Hash(rskTxHash));
            break;
        }

        i++;
    }
    // If tx fully signed
    if (hasEnoughSignatures(btcTx)) {
        logger.info("Tx fully signed {}. Hex: {}", btcTx, Hex.toHexString(btcTx.bitcoinSerialize()));
        removeUsedUTXOs(btcTx);
        provider.getRskTxsWaitingForSignatures().remove(new Sha3Hash(rskTxHash));
        provider.getRskTxsWaitingForBroadcasting().put(new Sha3Hash(rskTxHash),
                new ImmutablePair(btcTx, executionBlockNumber));
    } else {
        logger.debug("Tx not yet fully signed {}.", new Sha3Hash(rskTxHash));
    }
}

From source file:com.intuit.wasabi.assignment.impl.AssignmentsImplTest.java

@Test(expected = AssertionError.class)
public void testGetSingleAssignmentAssertExistingAssignment() {

    //Input/* ww w.  j ava  2s  .  c  o  m*/
    Application.Name appName = Application.Name.valueOf("Test");
    User.ID user = User.ID.valueOf("testUser");
    Experiment.ID id = Experiment.ID.newInstance();
    Experiment.Label label = Experiment.Label.valueOf("label");
    SegmentationProfile segmentationProfile = mock(SegmentationProfile.class);
    HttpHeaders headers = mock(HttpHeaders.class);

    //Mock dependent interactions
    Experiment experiment = mock(Experiment.class, RETURNS_DEEP_STUBS);
    when(experiment.getID()).thenReturn(id);
    when(experiment.getEndTime().getTime()).thenReturn(1000000L);
    when(experiment.getLabel()).thenReturn(label);

    List<Experiment> expList = newArrayList(experiment);

    PrioritizedExperimentList pExpList = new PrioritizedExperimentList();
    pExpList.addPrioritizedExperiment(PrioritizedExperiment.from(experiment, 1).build());
    Optional<PrioritizedExperimentList> prioritizedExperimentListOptional = Optional.of(pExpList);

    BucketList bucketList = new BucketList();
    bucketList
            .addBucket(Bucket.newInstance(id, Bucket.Label.valueOf("red")).withAllocationPercent(0.5).build());
    bucketList
            .addBucket(Bucket.newInstance(id, Bucket.Label.valueOf("blue")).withAllocationPercent(0.5).build());

    List<Experiment.ID> exclusionList = newArrayList();

    when(metadataCache.getExperimentById(id)).thenReturn(Optional.of(experiment));
    when(metadataCache.getExperimentsByAppName(appName)).thenReturn(expList);
    when(metadataCache.getPrioritizedExperimentListMap(appName)).thenReturn(prioritizedExperimentListOptional);
    when(metadataCache.getBucketList(id)).thenReturn(bucketList);
    when(metadataCache.getExclusionList(id)).thenReturn(exclusionList);

    when(experiment.getID()).thenReturn(id);
    when(experiment.getState()).thenReturn(Experiment.State.RUNNING);
    when(experiment.getEndTime().getTime()).thenReturn(new Date().getTime() + 1000000L);

    List<Pair<Experiment, String>> existingAssignments = newArrayList(
            new ImmutablePair<Experiment, String>(experiment, "red"));
    Map<Experiment.ID, Experiment> expMap = newHashMap();
    expMap.put(id, experiment);
    when(assignmentsRepository.getAssignments(user, appName, context, expMap)).thenReturn(existingAssignments);

    Assignment result = assignmentsImpl.doSingleAssignment(user, appName, label, context, true, true,
            segmentationProfile, headers);

    assertThat(result.getStatus(), is(Assignment.Status.EXISTING_ASSIGNMENT));
    verify(threadPoolExecutor, times(0)).execute(any(Runnable.class));
}

From source file:com.epam.ngb.cli.manager.command.handler.http.AbstractHTTPCommandHandler.java

private Pair<String, String> splitFilePath(String path) {
    String[] paths = path.split(INDEX_DELIMITER);
    if (paths.length > 2) {
        throw new IllegalArgumentException(getMessage(ILLEGAL_PATH_FORMAT, path));
    }/*from   w w w. j av a  2 s .  c  o  m*/
    if (paths.length == 1) {
        return new ImmutablePair<>(paths[0], null);
    } else {
        return new ImmutablePair<>(paths[0], paths[1]);
    }
}