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.google.dart.tools.internal.search.ui.FindReferencesAction.java

/**
 * Asks {@link SearchView} to execute query and display results.
 *//*from   w  w  w . j  av a  2s .co  m*/
private void doSearch(Element element, AstNode node) {
    // tweak
    element = DartElementUtil.getVariableIfSyntheticAccessor(element);
    if (element instanceof ImportElement) {
        element = ((ImportElement) element).getImportedLibrary();
    }
    // prepare name
    String name = null;
    if (node instanceof SimpleIdentifier) {
        name = ((SimpleIdentifier) node).getName();
    }
    // show search results
    try {
        final SearchEngine searchEngine = DartCore.getProjectManager().newSearchEngine();
        final Element searchElement = element;
        final String searchName = name;
        SearchView view = (SearchView) DartToolsPlugin.showView(SearchView.ID);
        if (view == null) {
            return;
        }
        view.showPage(new SearchMatchPage(view, "Searching for references...") {
            @Override
            protected void beforeRefresh() {
                super.beforeRefresh();
            }

            @Override
            protected boolean canUseFilterPotential() {
                return searchElement != null;
            }

            @Override
            protected IProject getCurrentProject() {
                return findCurrentProject();
            }

            @Override
            protected String getQueryElementName() {
                // no element
                if (searchElement == null) {
                    return searchName;
                }
                // constructor
                if (searchElement.getKind() == ElementKind.CONSTRUCTOR) {
                    String className = searchElement.getEnclosingElement().getDisplayName();
                    String constructorName = searchElement.getDisplayName();
                    if (StringUtils.isEmpty(constructorName)) {
                        return "constructor " + className + "()";
                    } else {
                        return "constructor " + className + "." + constructorName + "()";
                    }
                }
                // some other element
                return searchElement.getDisplayName();
            }

            @Override
            protected String getQueryKindName() {
                return "references";
            }

            @Override
            protected List<SearchMatch> runQuery() {
                List<SearchMatch> allMatches = Lists.newArrayList();
                if (searchElement != null) {
                    allMatches.addAll(findVariableElementDeclaration());
                    allMatches.addAll(findElementReferences(searchEngine, searchElement));
                }
                addUniqueNameReferences(allMatches, findNameReferences());
                allMatches = HierarchyUtils.getAccessibleMatches(searchElement, allMatches);
                allMatches = FindDeclarationsAction.getUniqueMatches(allMatches);
                return allMatches;
            }

            /**
             * Adds given "name" references only if there are no "exact" reference with same location.
             */
            private void addUniqueNameReferences(List<SearchMatch> result, List<SearchMatch> nameMatches) {
                // remember existing locations
                Set<Pair<Element, SourceRange>> existingRefs = Sets.newHashSet();
                for (SearchMatch match : result) {
                    existingRefs.add(ImmutablePair.of(match.getElement(), match.getSourceRange()));
                }
                // add new name references
                for (SearchMatch match : nameMatches) {
                    if (existingRefs.contains(ImmutablePair.of(match.getElement(), match.getSourceRange()))) {
                        continue;
                    }
                    result.add(match);
                }
            }

            private List<SearchMatch> findNameReferences() {
                if (searchElement != null) {
                    // only class members may have potential references
                    if (!(searchElement.getEnclosingElement() instanceof ClassElement)) {
                        return ImmutableList.of();
                    }
                    // check kind
                    ElementKind elementKind = searchElement.getKind();
                    if (elementKind != ElementKind.METHOD && elementKind != ElementKind.FIELD
                            && elementKind != ElementKind.GETTER && elementKind != ElementKind.SETTER) {
                        return ImmutableList.of();
                    }
                }
                // do search
                return searchEngine.searchQualifiedMemberReferences(searchName, null, new SearchFilter() {
                    @Override
                    public boolean passes(SearchMatch match) {
                        return match.getKind() == MatchKind.NAME_REFERENCE_UNRESOLVED;
                    }
                });
            }

            /**
             * For local variable and parameters it is interesting to see their declaration with
             * initializer and type.
             */
            private List<SearchMatch> findVariableElementDeclaration() {
                ElementKind elementKind = searchElement.getKind();
                if (elementKind != ElementKind.PARAMETER && elementKind != ElementKind.LOCAL_VARIABLE) {
                    return ImmutableList.of();
                }
                return ImmutableList.of(new SearchMatch(null, MatchKind.VARIABLE_WRITE, searchElement,
                        SourceRangeFactory.rangeElementName(searchElement)));
            }
        });
    } catch (Throwable e) {
        ExceptionHandler.handle(e, getText(), "Exception during search.");
    }
}

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

/**
 * Reruns the unification until all lazily added locations have propagated
 * and no more changes are detected.//from w w w  .ja v a 2  s .  c o m
 * 
 * {@link LocationIdentifier} are added lazily to
 * {@link ExtendedReferenceLocation} instances. If a location is added to an
 * already unified {@link ExtendedReferenceLocation}, the unification has to
 * be applied again to ensure correctness of the result.
 */
private void finalizePendingUnifications() {
    Deque<Pair<ReferenceLocation, ReferenceLocation>> worklist = new ArrayDeque<>();
    for (Map.Entry<ReferenceLocation, ReferenceLocation> locations : pendingUnifications.entries()) {
        ReferenceLocation refLoc1 = locations.getKey();
        ReferenceLocation refLoc2 = locations.getValue();

        int loc1Identifiers = refLoc1.getIdentifiers().size();
        int loc2Identifiers = refLoc2.getIdentifiers().size();

        if (loc1Identifiers != loc2Identifiers) {
            worklist.addFirst(ImmutablePair.of(refLoc1, refLoc2));
        }
    }

    while (!worklist.isEmpty()) {
        Pair<ReferenceLocation, ReferenceLocation> locations = worklist.removeFirst();
        ReferenceLocation loc1 = locations.getLeft();
        ReferenceLocation loc2 = locations.getRight();

        int previousIdentifiersLoc1 = loc1.getIdentifiers().size();
        int previousIdentifiersLoc2 = loc2.getIdentifiers().size();
        unify(loc1, loc2);

        updateUnificationWorklist(worklist, previousIdentifiersLoc1, loc1, loc2);
        updateUnificationWorklist(worklist, previousIdentifiersLoc2, loc2, loc1);
    }
}

From source file:com.joyent.manta.http.ApacheHttpGetResponseEntityContentContinuatorTest.java

@Test(expectedExceptions = ProtocolException.class)
public void validateResponseExpectsContentRangeHeader() throws ProtocolException {
    STUB_CONTINUATOR.validateResponseWithMarker(ImmutablePair.of(STUB_ETAG, null));
}

From source file:com.joyent.manta.http.ApacheHttpGetResponseEntityContentContinuatorTest.java

@Test(expectedExceptions = ProtocolException.class)
public void validateResponseExpectsETagHeader() throws ProtocolException {
    STUB_CONTINUATOR.validateResponseWithMarker(ImmutablePair.of(null, STUB_CONTENT_RANGE));
}

From source file:com.wrmsr.wava.transform.Transforms.java

public static com.wrmsr.wava.core.unit.Function eliminateUnreferencedLocals(
        com.wrmsr.wava.core.unit.Function function) {
    LocalAnalysis.Entry la = LocalAnalysis.analyze(function.getBody()).get(function.getBody());
    List<Index> indices = new ArrayList<>(Sets.union(la.getLocalGets(), la.getLocalPuts()));
    Collections.sort(indices);//from  w  w w  .ja v a 2s. co  m
    Locals locals = Locals
            .of(function.getLocals().getList().stream().filter(l -> indices.contains(l.getIndex()))
                    .map(l -> ImmutablePair.of(l.getName(), l.getType())).collect(toImmutableList()));
    Map<Index, Index> indexMap = enumerate(indices.stream())
            .collect(toImmutableMap(i -> i.getItem(), i -> Index.of(i.getIndex())));
    return new com.wrmsr.wava.core.unit.Function(function.getName(), function.getResult(),
            function.getArgCount(), locals, remapLocals(function.getBody(), indexMap));
}

From source file:com.joyent.manta.http.ApacheHttpGetResponseEntityContentContinuatorTest.java

@Test(expectedExceptions = ProtocolException.class)
public void validateResponseExpectsMatchingResponseRange() throws ProtocolException {
    final HttpRange.Response badContentRange = new HttpRange.Response(0, STUB_CONTENT_LENGTH,
            STUB_CONTENT_LENGTH + 1);/* ww w .  j  ava2  s .  co  m*/
    STUB_CONTINUATOR.validateResponseWithMarker(ImmutablePair.of(STUB_ETAG, badContentRange));
}

From source file:com.wrmsr.wava.TestOutlining.java

public static Pair<Function, Function> inlineThatOneSwitch(Function function, int num) {
    Node body = function.getBody();

    LocalAnalysis loa = LocalAnalysis.analyze(body);
    ControlTransferAnalysis cfa = ControlTransferAnalysis.analyze(body);
    ValueTypeAnalysis vta = ValueTypeAnalysis.analyze(body, false);

    Map<Node, Optional<Node>> parentsByNode = Analyses.getParents(body);
    Map<Node, Integer> totalChildrenByNode = Analyses.getChildCounts(body);
    Map<Name, Node> nodesByName = Analyses.getNamedNodes(body);

    Node maxNode = body;//from  w  ww .  j  ava2 s  .  c  o m
    int maxDiff = 0;

    Node cur = body;
    while (true) {
        Optional<Node> maxChild = cur.getChildren().stream()
                .max((l, r) -> Integer.compare(totalChildrenByNode.get(l), totalChildrenByNode.get(r)));
        if (!maxChild.isPresent()) {
            break;
        }
        int diff = totalChildrenByNode.get(cur) - totalChildrenByNode.get(maxChild.get());
        if (diff > maxDiff) {
            maxNode = cur;
            maxDiff = diff;
        }
        cur = maxChild.get();
    }

    List<Node> alsdfj = new ArrayList<>(maxNode.getChildren());
    Collections.sort(alsdfj,
            (l, r) -> -Integer.compare(totalChildrenByNode.get(l), totalChildrenByNode.get(r)));

    Index externalRetControl;
    Index externalRetValue;
    List<Local> localList;

    if (function.getLocals().getLocalsByName().containsKey(Name.of("_external$control"))) {
        externalRetControl = function.getLocals().getLocal(Name.of("_external$control")).getIndex();
        externalRetValue = function.getLocals().getLocal(Name.of("_external$value")).getIndex();
        localList = function.getLocals().getList();
    } else {
        externalRetControl = Index.of(function.getLocals().getList().size());
        externalRetValue = Index.of(function.getLocals().getList().size() + 1);
        localList = ImmutableList.<Local>builder().addAll(function.getLocals().getList())
                .add(new Local(Name.of("_external$control"), externalRetControl, Type.I32))
                .add(new Local(Name.of("_external$value"), externalRetValue, Type.I64)).build();
    }

    Node node = maxNode;
    if (maxNode instanceof Switch) {
        Switch switchNode = (Switch) node;
        Optional<Switch.Entry> maxEntry = switchNode.getEntries().stream().max((l, r) -> Integer
                .compare(totalChildrenByNode.get(l.getBody()), totalChildrenByNode.get(r.getBody())));
        node = maxEntry.get().getBody();
    }

    Outlining.OutlinedFunction of = Outlining.outlineFunction(function, node,
            Name.of(function.getName().get() + "$outlined$" + num), externalRetControl, externalRetValue, loa,
            cfa, vta, parentsByNode, nodesByName);

    Function newFunc = new Function(function.getName(), function.getResult(), function.getArgCount(),
            new Locals(localList), Transforms.replaceNode(function.getBody(), node, of.getCallsite(), true));

    return ImmutablePair.of(newFunc, of.getFunction());
}

From source file:com.joyent.manta.http.ApacheHttpGetResponseEntityContentContinuatorTest.java

@Test(expectedExceptions = ProtocolException.class)
public void validateResponseExpectsMatchingETag() throws ProtocolException {
    final String badEtag = STUB_ETAG.substring(1);
    STUB_CONTINUATOR.validateResponseWithMarker(ImmutablePair.of(badEtag, STUB_CONTENT_RANGE));
}

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

private void updateUnificationWorklist(Deque<Pair<ReferenceLocation, ReferenceLocation>> worklist,
        int previousIdentifiersSize, ReferenceLocation location, ReferenceLocation unificationPartner) {
    int newIdentifiersSize = location.getIdentifiers().size();
    if (newIdentifiersSize != previousIdentifiersSize) {
        for (ReferenceLocation dependentLocation : pendingUnifications.get(location)) {
            if (dependentLocation != unificationPartner) {
                worklist.addFirst(ImmutablePair.of(location, dependentLocation));
            }/*from   ww  w.  ja  va2 s  . c  o  m*/
        }
    }
}

From source file:io.lavagna.web.api.CardDataControllerTest.java

@Test
public void uploadFiles() throws NoSuchAlgorithmException, IOException {
    MultipartFile f = mock(MultipartFile.class);
    when(f.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[] { 42, 42, 42, 42, 84, 84, 84 }));
    when(cardDataService.createFile(any(String.class), any(String.class), any(Integer.class),
            any(Integer.class), any(InputStream.class), any(String.class), any(User.class), any(Date.class)))
                    .thenReturn(ImmutablePair.of(true, mock(CardData.class)));
    List<MultipartFile> files = Arrays.asList(f);
    cardDataController.uploadFiles(cardId, files, user, new MockHttpServletResponse());
}