Example usage for java.util LinkedList addFirst

List of usage examples for java.util LinkedList addFirst

Introduction

In this page you can find the example usage for java.util LinkedList addFirst.

Prototype

public void addFirst(E e) 

Source Link

Document

Inserts the specified element at the beginning of this list.

Usage

From source file:net.mybox.mybox.ClientStatus.java

public synchronized void FullSync() {

    printMessage("disabling listener");
    disableDirListener(); // hack while incoming set gets figured out

    setStatus(ClientStatus.SYNCING);//  www  .  ja  v a  2  s  .com

    printMessage("Full sync started  " + Common.now());

    // TODO: if lastSysc is 0 or bogus, favoror file creations over deletions
    // TODO: update all time comparisons to respect server/client time differences

    populateLocalFileList();
    boolean listReturned = serverDiscussion(Common.Signal.requestServerFileList,
            Common.Signal.requestServerFileList_response, null);

    if (!listReturned) {
        printErrorExit("requestServerFileList did not return in time");
    }

    System.out.println("comparing C=" + C.size() + " to S=" + S.size());

    LinkedList<MyFile> SendToServer = new LinkedList<MyFile>();

    // strange case = when there is the same name item but it is a file on the client and dir on server

    for (String name : C.keySet()) {

        MyFile c = C.get(name);

        if (S.containsKey(name)) {
            MyFile s = S.get(name);

            // if it is not a directory and the times are different, compare times
            if (!(new File(localDir + "/" + name)).isDirectory() && c.modtime != s.modtime) {

                System.out
                        .println(name + " " + lastSync + " c.modtime=" + c.modtime + " s.modtime=" + s.modtime);

                if (c.modtime > lastSync) {
                    if (s.modtime > lastSync) {
                        System.out.println(name + " = conflict type 1");
                    } else {
                        System.out.println(name + " = transfer from client to server 1");
                        SendToServer.addFirst(c);
                    }
                } else {
                    if (s.modtime > c.modtime) {
                        System.out.println(name + " = transfer from server to client 1");
                        requestFile(s.name);
                    } else {
                        System.out.println(name + " = conflict type 2");
                    }
                }
            }
            S.remove(name);
        } else {

            if (c.modtime > lastSync) {

                if ((new File(localDir + "/" + name)).isDirectory()) {
                    System.out.println(name + " = create directory on server");
                    createDirectoryOnServer(name);
                } else {
                    System.out.println(name + " = transfer from client to server 2");
                    SendToServer.addFirst(c);
                }

            } else {

                if ((new File(localDir + "/" + name)).isDirectory()) {
                    System.out.println(name + " = remove directory on client");
                    Common.deleteLocalDirectory(new File(localDir + "/" + name));
                } else {
                    System.out.println(name + " = remove from client");
                    Common.deleteLocal(localDir + "/" + name);
                }

            }

        }
    }

    for (String name : S.keySet()) { // which is now S-C
        MyFile s = S.get(name);

        if (s.modtime > lastSync) {

            if (s.type.equals("directory")) {
                System.out.println(name + " = create local directory on client");
                Common.createLocalDirectory(localDir + "/" + name);
            } else {
                System.out.println(name + " = transfer from server to client 2");
                requestFile(s.name);
            }

        } else {

            if (s.type.equals("directory")) {
                System.out.println(name + " = remove directory on server");
                deleteOnServer(s.name);
            } else {
                System.out.println(name + " = remove from server");
                deleteOnServer(s.name);
            }

        }
    }

    System.out.println("SendToServer");
    for (MyFile item : SendToServer) {
        outQueue.addFirst(item);
        System.out.println(item);
    }

    checkQueue();

    updateLastSync(); // TODO: this shoud actually happen after all inbound have finished

    System.out.println("Setting lasySync to " + lastSync);

    C.clear();
    S.clear();

    printMessage("enableing listener since sync is done");
    enableDirListener();

    printMessage("Sync finished " + Common.now());

    setStatus(ClientStatus.READY);
}

From source file:com.netscape.cmsutil.crypto.CryptoUtil.java

/**
 * Sorts certificate chain from root to leaf.
 *
 * This method sorts an array of certificates (e.g. from a PKCS #7
 * data) that represents a certificate chain from root to leaf
 * according to the subject DNs and issuer DNs.
 *
 * The input array is a set of certificates that are part of a
 * chain but not in specific order./*  w  ww.j av a 2  s.c o m*/
 *
 * The result is a new array that contains the certificate chain
 * sorted from root to leaf. The input array is unchanged.
 *
 * @param certs input array of certificates
 * @return new array containing sorted certificates
 */
public static java.security.cert.X509Certificate[] sortCertificateChain(
        java.security.cert.X509Certificate[] certs) throws Exception {

    // lookup map: subject DN -> cert
    Map<String, java.security.cert.X509Certificate> certMap = new LinkedHashMap<>();

    // hierarchy map: subject DN -> issuer DN
    Map<String, String> parentMap = new HashMap<>();

    // reverse hierarchy map: issuer DN -> subject DN
    Map<String, String> childMap = new HashMap<>();

    // build maps
    for (java.security.cert.X509Certificate cert : certs) {

        String subjectDN = cert.getSubjectDN().toString();
        String issuerDN = cert.getIssuerDN().toString();

        if (certMap.containsKey(subjectDN)) {
            throw new Exception("Duplicate certificate: " + subjectDN);
        }

        certMap.put(subjectDN, cert);

        // ignore self-signed certificate
        if (subjectDN.equals(issuerDN))
            continue;

        if (childMap.containsKey(issuerDN)) {
            throw new Exception("Branched chain: " + issuerDN);
        }

        parentMap.put(subjectDN, issuerDN);
        childMap.put(issuerDN, subjectDN);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Certificates:");
        for (String subjectDN : certMap.keySet()) {
            logger.debug(" - " + subjectDN);

            String parent = parentMap.get(subjectDN);
            if (parent != null)
                logger.debug("   parent: " + parent);

            String child = childMap.get(subjectDN);
            if (child != null)
                logger.debug("   child: " + child);
        }
    }

    // find leaf cert
    List<String> leafCerts = new ArrayList<>();

    for (String subjectDN : certMap.keySet()) {

        // if cert has a child, skip
        if (childMap.containsKey(subjectDN))
            continue;

        // found leaf cert
        leafCerts.add(subjectDN);
    }

    if (leafCerts.isEmpty()) {
        throw new Exception("Unable to find leaf certificate");
    }

    if (leafCerts.size() > 1) {
        StringBuilder sb = new StringBuilder();
        for (String subjectDN : leafCerts) {
            if (sb.length() > 0)
                sb.append(", ");
            sb.append("[" + subjectDN + "]");
        }
        throw new Exception("Multiple leaf certificates: " + sb);
    }

    // build sorted chain
    LinkedList<java.security.cert.X509Certificate> chain = new LinkedList<>();

    // start from leaf
    String current = leafCerts.get(0);

    while (current != null) {

        java.security.cert.X509Certificate cert = certMap.get(current);

        if (cert == null) {
            // incomplete chain
            break;
        }

        // add to the beginning of chain
        chain.addFirst(cert);

        // follow parent to root
        current = parentMap.get(current);
    }

    return chain.toArray(new java.security.cert.X509Certificate[chain.size()]);
}

From source file:org.alfresco.web.forms.xforms.Schema2XFormsProperties.java

public ResourceBundle getResourceBundle(final Form form, final Locale locale) {
    final LinkedList<ResourceBundle> bundles = new LinkedList<ResourceBundle>();
    for (String location : this.locations) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        location = location.replace("${form.name}",
                (NamespaceService.CONTENT_MODEL_PREFIX + ':' + form.getName()));
        if (location.startsWith("alfresco:")) {
            location = location.substring("alfresco:".length());
            loader = new ClassLoader(loader) {
                public InputStream getResourceAsStream(String name) {
                    LOGGER.debug("loading resource " + name);
                    final ResultSet results = searchService.query(Repository.getStoreRef(),
                            SearchService.LANGUAGE_LUCENE, "PATH:\"" + name + "\"");
                    try {
                        LOGGER.debug("search returned " + results.length() + " results");
                        if (results.length() == 1) {
                            final NodeRef nr = results.getNodeRef(0);
                            final ContentReader reader = contentService.getReader(nr,
                                    ContentModel.PROP_CONTENT);
                            return reader.getContentInputStream();
                        } else {
                            return super.getResourceAsStream(name);
                        }//from   www.jav a  2s  .co m
                    } finally {
                        results.close();
                    }
                }
            };
        } else if (location.startsWith("classpath:")) {
            location = location.substring("classpath:".length());
        }

        LOGGER.debug("using loader " + loader + " for location " + location);
        try {
            final ResourceBundle rb = ResourceBundle.getBundle(location, locale, loader);
            LOGGER.debug("found bundle " + rb + " for location " + location);
            bundles.addFirst(rb);
        } catch (MissingResourceException mse) {
            LOGGER.debug("unable to located bundle at " + location + ": " + mse.getMessage());
        }
    }

    ResourceBundle result = null;
    for (ResourceBundle rb : bundles) {
        result = (result == null ? rb : new ResourceBundleWrapper(rb, result));
    }
    return result;
}

From source file:gate.creole.tokeniser.SimpleTokeniser.java

/** Converts the FSM from a non-deterministic to a deterministic one by
 * eliminating all the unrestricted transitions.
 *///from w  ww . ja v a2 s.  co  m
void eliminateVoidTransitions() throws TokeniserException {

    //kalina:clear() faster than init() which is called with init()
    newStates.clear();
    Set<Set<FSMState>> sdStates = new HashSet<Set<FSMState>>();
    LinkedList<Set<FSMState>> unmarkedDStates = new LinkedList<Set<FSMState>>();
    DFSMState dCurrentState = new DFSMState(this);
    Set<FSMState> sdCurrentState = new HashSet<FSMState>();

    sdCurrentState.add(initialState);
    sdCurrentState = lambdaClosure(sdCurrentState);
    newStates.put(sdCurrentState, dCurrentState);
    sdStates.add(sdCurrentState);

    //find out if the new state is a final one
    Iterator<FSMState> innerStatesIter = sdCurrentState.iterator();
    String rhs;
    FSMState currentInnerState;
    Set<String> rhsClashSet = new HashSet<String>();
    boolean newRhs = false;

    while (innerStatesIter.hasNext()) {
        currentInnerState = innerStatesIter.next();
        if (currentInnerState.isFinal()) {
            rhs = currentInnerState.getRhs();
            rhsClashSet.add(rhs);
            dCurrentState.rhs = rhs;
            newRhs = true;
        }
    }

    if (rhsClashSet.size() > 1) {
        Err.println("Warning, rule clash: " + rhsClashSet + "\nSelected last definition: " + dCurrentState.rhs);
    }

    if (newRhs)
        dCurrentState.buildTokenDesc();
    rhsClashSet.clear();
    unmarkedDStates.addFirst(sdCurrentState);
    dInitialState = dCurrentState;
    Set<FSMState> nextSet;

    while (!unmarkedDStates.isEmpty()) {
        //Out.println("\n\n=====================" + unmarkedDStates.size());
        sdCurrentState = unmarkedDStates.removeFirst();
        for (int type = 0; type < maxTypeId; type++) {
            //Out.print(type);
            nextSet = new HashSet<FSMState>();
            innerStatesIter = sdCurrentState.iterator();

            while (innerStatesIter.hasNext()) {
                currentInnerState = innerStatesIter.next();
                Set<FSMState> tempSet = currentInnerState.nextSet(type);
                if (null != tempSet)
                    nextSet.addAll(tempSet);
            } //while(innerStatesIter.hasNext())

            if (!nextSet.isEmpty()) {
                nextSet = lambdaClosure(nextSet);
                dCurrentState = newStates.get(nextSet);

                if (dCurrentState == null) {

                    //we have a new DFSMState
                    dCurrentState = new DFSMState(this);
                    sdStates.add(nextSet);
                    unmarkedDStates.add(nextSet);

                    //check to see whether the new state is a final one
                    innerStatesIter = nextSet.iterator();
                    newRhs = false;

                    while (innerStatesIter.hasNext()) {
                        currentInnerState = innerStatesIter.next();
                        if (currentInnerState.isFinal()) {
                            rhs = currentInnerState.getRhs();
                            rhsClashSet.add(rhs);
                            dCurrentState.rhs = rhs;
                            newRhs = true;
                        }
                    }

                    if (rhsClashSet.size() > 1) {
                        Err.println("Warning, rule clash: " + rhsClashSet + "\nSelected last definition: "
                                + dCurrentState.rhs);
                    }

                    if (newRhs)
                        dCurrentState.buildTokenDesc();
                    rhsClashSet.clear();
                    newStates.put(nextSet, dCurrentState);
                }
                newStates.get(sdCurrentState).put(type, dCurrentState);
            } // if(!nextSet.isEmpty())

        } // for(byte type = 0; type < 256; type++)

    } // while(!unmarkedDStates.isEmpty())

}

From source file:net.spfbl.data.Block.java

public static TreeSet<String> getAllTokens(String value) {
    TreeSet<String> blockSet = new TreeSet<String>();
    if (Subnet.isValidIP(value)) {
        String ip = Subnet.normalizeIP(value);
        if (SET.contains(ip)) {
            blockSet.add(ip);/*from   ww  w. j  a  va2  s . co m*/
        }
    } else if (Subnet.isValidCIDR(value)) {
        String cidr = Subnet.normalizeCIDR(value);
        if (CIDR.contains((String) null, cidr)) {
            blockSet.add(cidr);
        }
        TreeSet<String> set = SET.getAll();
        for (String ip : set) {
            if (Subnet.containsIP(cidr, ip)) {
                blockSet.add(ip);
            }
        }
        for (String ip : set) {
            if (SubnetIPv6.containsIP(cidr, ip)) {
                blockSet.add(ip);
            }
        }
    } else if (Domain.isHostname(value)) {
        LinkedList<String> regexList = new LinkedList<String>();
        String host = Domain.normalizeHostname(value, true);
        do {
            int index = host.indexOf('.') + 1;
            host = host.substring(index);
            if (Block.dropExact('.' + host)) {
                blockSet.add('.' + host);
                regexList.addFirst('.' + host);
            }
        } while (host.contains("."));
    } else if (SET.contains(value)) {
        blockSet.add(value);
    }
    return blockSet;
}

From source file:org.trnltk.experiment.morphology.ambiguity.DataDiffUtil.java

/**
 * Find the differences between two texts.  Simplifies the problem by
 * stripping any common prefix or suffix off the texts before diffing.
 *
 * @param list1      Old string to be diffed.
 * @param list2      New string to be diffed.
 * @param checklines Speedup flag.  If false, then don't run a
 *                   line-level diff first to identify the changed areas.
 *                   If true, then run a faster slightly less optimal diff.
 * @param deadline   Time when the diff should be complete by.  Used
 *                   internally for recursive calls.  Users should set DiffTimeout instead.
 * @return Linked List of Diff objects.//ww w .j av  a  2 s  .co m
 */
private LinkedList<Diff<T>> diff_main(List<T> list1, List<T> list2, boolean checklines, long deadline) {
    // Check for null inputs.
    if (list1 == null || list2 == null) {
        throw new IllegalArgumentException("Null inputs. (diff_main)");
    }

    // Check for equality (speedup).
    LinkedList<Diff<T>> diffs;
    if (list1.equals(list2)) {
        diffs = new LinkedList<Diff<T>>();
        if (list1.size() != 0) {
            diffs.add(new Diff<T>(Operation.EQUAL, list1));
        }
        return diffs;
    }

    // Trim off common prefix (speedup).
    int commonlength = diff_commonPrefix(list1, list2);
    List<T> commonprefix = list1.subList(0, commonlength);
    list1 = list1.subList(commonlength, list1.size());
    list2 = list2.subList(commonlength, list2.size());

    // Trim off common suffix (speedup).
    commonlength = diff_commonSuffix(list1, list2);
    List<T> commonsuffix = list1.subList(list1.size() - commonlength, list1.size());
    list1 = list1.subList(0, list1.size() - commonlength);
    list2 = list2.subList(0, list2.size() - commonlength);

    // Compute the diff on the middle block.
    diffs = diff_compute(list1, list2, checklines, deadline);

    // Restore the prefix and suffix.
    if (commonprefix.size() != 0) {
        diffs.addFirst(new Diff<T>(Operation.EQUAL, commonprefix));
    }
    if (commonsuffix.size() != 0) {
        diffs.addLast(new Diff<T>(Operation.EQUAL, commonsuffix));
    }

    diff_cleanupMerge(diffs);
    return diffs;
}

From source file:org.lockss.plugin.base.DefaultUrlCacher.java

protected CacheException validate(CIProperties headers, RepositoryNode node, long size) throws CacheException {
    LinkedList<Pair<String, Exception>> validationFailures = new LinkedList<Pair<String, Exception>>();

    // First check actual length = Content-Length header if any
    long contLen = getContentLength();
    if (contLen >= 0 && contLen != size) {
        Alert alert = Alert.auAlert(Alert.FILE_VERIFICATION, au);
        alert.setAttribute(Alert.ATTR_URL, getFetchUrl());
        String msg = "File size (" + size + ") differs from Content-Length header (" + contLen + "): "
                + getFetchUrl();//  w ww.j  a  va2  s . c  om
        alert.setAttribute(Alert.ATTR_TEXT, msg);
        raiseAlert(alert);
        validationFailures.add(new ImmutablePair(getUrl(), new ContentValidationException.WrongLength(msg)));
    }

    // 2nd, empty file
    if (size == 0) {
        Exception ex = new ContentValidationException.EmptyFile("Empty file stored");
        validationFailures.add(new ImmutablePair(getUrl(), ex));
    }

    // 3rd plugin-supplied ContentValidator.  Any
    // ContentValidationException it throws will take precedence over the
    // previous (wrong length, empty), but an unexpected exception will not
    // take precedence.
    String contentType = getContentType();
    ContentValidatorFactory cvfact = au.getContentValidatorFactory(contentType);
    if (cvfact != null) {
        ContentValidator cv = cvfact.createContentValidator(au, contentType);
        if (cv != null) {
            CachedUrl cu = getTempCachedUrl(headers, size, node);
            try {
                cv.validate(cu);
            } catch (ContentValidationException e) {
                logger.debug2("Validation error1", e);
                // Plugin-triggered ContentValidationException goes first
                validationFailures.addFirst(new ImmutablePair(getUrl(), e));
            } catch (Exception e) {
                logger.debug2("Validation error2", e);
                // Unexpected error in validator goes first
                validationFailures.addFirst(
                        new ImmutablePair(getUrl(), new ContentValidationException.ValidatorExeception(e)));
            } finally {
                cu.release();
            }
        }
    }
    return firstMappedException(validationFailures);
}

From source file:umich.ms.batmass.filesupport.core.actions.importing.ImportFileByCategory.java

private List<BMFileFilter> createFileFilters(String category) {
    List<FileTypeResolver> resolvers = FileTypeResolverUtils.getTypeResolvers(category);
    String baseDesc = getCategoryDisplayName();
    LinkedList<BMFileFilter> filters = new LinkedList<>();
    if (resolvers.isEmpty()) {
        filters.add(new BMFileFilter(null) {
            @Override/*from w w  w . ja  v a 2s  . co m*/
            public String getShortDescription() {
                return "UNDEFINED";
            }

            @Override
            public String getDescription() {
                return "No resolvers were found for this filetype category";
            }
        });
        return filters;
    }

    for (FileTypeResolver resolver : resolvers) {
        filters.add(resolver.getFileFilter());
    }

    List<String> shortDescs = new ArrayList<>(filters.size());
    for (BMFileFilter bmff : filters) {
        shortDescs.add(bmff.getShortDescription());
    }
    Collections.sort(shortDescs);

    // creating the composite filter for all recognized files
    StringBuilder sb = new StringBuilder();
    sb.append(baseDesc).append(" (");
    sb.append(shortDescs.get(0));
    if (shortDescs.size() > 1) {
        for (int i = 1; i < shortDescs.size(); i++) {
            sb.append(", ").append(shortDescs.get(i));
        }
    }
    sb.append(")");

    List<IOFileFilter> ioFileFilters = new ArrayList<>(filters.size());
    for (BMFileFilter bmff : filters) {
        ioFileFilters.add(bmff.getFileFilter());
    }

    // add a filter that allows showing directories when "all supported files" option in the filechooser is selected
    ioFileFilters.add(new BMDirectoryFileFilter().getFileFilter());

    OrFileFilter orFileFilter = new OrFileFilter(ioFileFilters);
    final String allFiltersDesc = sb.toString();
    BMFileFilter combinedFilter = new BMFileFilter(orFileFilter) {
        @Override
        public String getShortDescription() {
            return allFiltersDesc;
        }

        @Override
        public String getDescription() {
            return "Any supported file";
        }
    };
    filters.addFirst(combinedFilter);
    return filters;
}

From source file:com.alvermont.terraj.stargen.dole.DoleAccrete.java

/**
 * Update the band structure by removing or splitting bands from which
 * the planet would have accreted mass./*from   w  ww  . j  a  v a 2  s .  c om*/
 *
 * @param list The dust list to be updated
 * @param p The planet being constructed
 */
protected void updateBands(LinkedList<DustRecord> list, DolePlanetRecord p) {
    final double min = p.getRMin(); /* minimum and maximum reach of the planet */
    final double max = p.getRMax();

    final Iterator<DustRecord> i = list.iterator();

    List<DustRecord> pendingPrepend = null;

    while (i.hasNext()) {
        final DustRecord b = i.next();

        /* check for trivial rejection */
        if ((max < b.getInnerEdge()) || (min > b.getOuterEdge())) {
            continue;
        }

        if (max < b.getOuterEdge()) {
            if (min > b.getInnerEdge()) {
                /* interval within band, so split it */
                final DustRecord newband = new DustRecord(b.getInnerEdge(), min);
                b.setInnerEdge(max);

                if (pendingPrepend == null) {
                    pendingPrepend = new ArrayList<DustRecord>();
                }

                pendingPrepend.add(newband);
            } else {
                /* interval overlaps inner edge */
                b.setInnerEdge(max);
            }
        } else {
            if (min > b.getInnerEdge()) {
                /* interval overlaps outer edge */
                b.setOuterEdge(min);
            } else {
                /* interval contains band, so kill it */
                i.remove();
            }
        }
    }

    // now add the elements we couldn't because we'd have mucked up the iterator
    // java list/iterator semantics can be v. annoying sometimes
    if (pendingPrepend != null) {
        for (DustRecord newband : pendingPrepend) {
            list.addFirst(newband);
        }
    }
}

From source file:edu.uci.ics.hyracks.algebricks.rewriter.rules.PushSelectIntoJoinRule.java

@Override
public boolean rewritePost(Mutable<ILogicalOperator> opRef, IOptimizationContext context)
        throws AlgebricksException {
    Collection<LogicalVariable> joinLiveVarsLeft = new HashSet<LogicalVariable>();
    Collection<LogicalVariable> joinLiveVarsRight = new HashSet<LogicalVariable>();
    Collection<LogicalVariable> liveInOpsToPushLeft = new HashSet<LogicalVariable>();
    Collection<LogicalVariable> liveInOpsToPushRight = new HashSet<LogicalVariable>();

    List<ILogicalOperator> pushedOnLeft = new ArrayList<ILogicalOperator>();
    List<ILogicalOperator> pushedOnRight = new ArrayList<ILogicalOperator>();
    LinkedList<ILogicalOperator> notPushedStack = new LinkedList<ILogicalOperator>();
    Collection<LogicalVariable> usedVars = new HashSet<LogicalVariable>();
    Collection<LogicalVariable> producedVars = new HashSet<LogicalVariable>();

    AbstractLogicalOperator op = (AbstractLogicalOperator) opRef.getValue();
    if (op.getOperatorTag() != LogicalOperatorTag.SELECT) {
        return false;
    }// w  w  w  .  ja  v a 2  s .c  o  m
    SelectOperator select = (SelectOperator) op;
    Mutable<ILogicalOperator> opRef2 = op.getInputs().get(0);
    AbstractLogicalOperator son = (AbstractLogicalOperator) opRef2.getValue();
    AbstractLogicalOperator op2 = son;
    boolean needToPushOps = false;
    while (son.isMap()) {
        needToPushOps = true;
        Mutable<ILogicalOperator> opRefLink = son.getInputs().get(0);
        son = (AbstractLogicalOperator) opRefLink.getValue();
    }

    if (son.getOperatorTag() != LogicalOperatorTag.INNERJOIN
            && son.getOperatorTag() != LogicalOperatorTag.LEFTOUTERJOIN) {
        return false;
    }
    boolean isLoj = son.getOperatorTag() == LogicalOperatorTag.LEFTOUTERJOIN;
    AbstractBinaryJoinOperator join = (AbstractBinaryJoinOperator) son;

    Mutable<ILogicalOperator> joinBranchLeftRef = join.getInputs().get(0);
    Mutable<ILogicalOperator> joinBranchRightRef = join.getInputs().get(1);

    if (needToPushOps) {
        ILogicalOperator joinBranchLeft = joinBranchLeftRef.getValue();
        ILogicalOperator joinBranchRight = joinBranchRightRef.getValue();
        VariableUtilities.getLiveVariables(joinBranchLeft, joinLiveVarsLeft);
        VariableUtilities.getLiveVariables(joinBranchRight, joinLiveVarsRight);
        Mutable<ILogicalOperator> opIterRef = opRef2;
        ILogicalOperator opIter = op2;
        while (opIter != join) {
            LogicalOperatorTag tag = ((AbstractLogicalOperator) opIter).getOperatorTag();
            if (tag == LogicalOperatorTag.PROJECT) {
                notPushedStack.addFirst(opIter);
            } else {
                VariableUtilities.getUsedVariables(opIter, usedVars);
                VariableUtilities.getProducedVariables(opIter, producedVars);
                if (joinLiveVarsLeft.containsAll(usedVars)) {
                    pushedOnLeft.add(opIter);
                    liveInOpsToPushLeft.addAll(producedVars);
                } else if (joinLiveVarsRight.containsAll(usedVars)) {
                    pushedOnRight.add(opIter);
                    liveInOpsToPushRight.addAll(producedVars);
                } else {
                    return false;
                }
            }
            opIterRef = opIter.getInputs().get(0);
            opIter = opIterRef.getValue();
        }
        if (isLoj && pushedOnLeft.isEmpty()) {
            return false;
        }
    }

    boolean intersectsAllBranches = true;
    boolean[] intersectsBranch = new boolean[join.getInputs().size()];
    LinkedList<LogicalVariable> selectVars = new LinkedList<LogicalVariable>();
    select.getCondition().getValue().getUsedVariables(selectVars);
    int i = 0;
    for (Mutable<ILogicalOperator> branch : join.getInputs()) {
        LinkedList<LogicalVariable> branchVars = new LinkedList<LogicalVariable>();
        VariableUtilities.getLiveVariables(branch.getValue(), branchVars);
        if (i == 0) {
            branchVars.addAll(liveInOpsToPushLeft);
        } else {
            branchVars.addAll(liveInOpsToPushRight);
        }
        if (OperatorPropertiesUtil.disjoint(selectVars, branchVars)) {
            intersectsAllBranches = false;
        } else {
            intersectsBranch[i] = true;
        }
        i++;
    }
    if (!intersectsBranch[0] && !intersectsBranch[1]) {
        return false;
    }
    if (needToPushOps) {
        pushOps(pushedOnLeft, joinBranchLeftRef, context);
        pushOps(pushedOnRight, joinBranchRightRef, context);
    }
    if (intersectsAllBranches) {
        addCondToJoin(select, join, context);
    } else { // push down
        Iterator<Mutable<ILogicalOperator>> branchIter = join.getInputs().iterator();
        ILogicalExpression selectCondition = select.getCondition().getValue();
        boolean lojToInner = false;
        for (int j = 0; j < intersectsBranch.length; j++) {
            Mutable<ILogicalOperator> branch = branchIter.next();
            boolean inter = intersectsBranch[j];
            if (inter) {
                if (j > 0 && isLoj) {
                    // if a left outer join, if the select condition is not-null filtering,
                    // we rewrite left outer join
                    // to inner join for this case.
                    if (containsNotNullFiltering(selectCondition)) {
                        lojToInner = true;
                    }
                }
                if ((j > 0 && isLoj) && containsNullFiltering(selectCondition)) {
                    // Select is-null($$var) cannot be pushed in the right branch of a LOJ;
                    notPushedStack.addFirst(select);
                } else {
                    // Conditions for the left branch can always be pushed.
                    // Other conditions can be pushed to the right branch of a LOJ.
                    copySelectToBranch(select, branch, context);
                }
            }
        }
        if (lojToInner) {
            // Rewrites left outer join  to inner join.
            InnerJoinOperator innerJoin = new InnerJoinOperator(join.getCondition());
            innerJoin.getInputs().addAll(join.getInputs());
            join = innerJoin;
            context.computeAndSetTypeEnvironmentForOperator(join);
        }
    }
    ILogicalOperator top = join;
    for (ILogicalOperator npOp : notPushedStack) {
        List<Mutable<ILogicalOperator>> npInpList = npOp.getInputs();
        npInpList.clear();
        npInpList.add(new MutableObject<ILogicalOperator>(top));
        context.computeAndSetTypeEnvironmentForOperator(npOp);
        top = npOp;
    }
    opRef.setValue(top);
    return true;

}