Example usage for java.util LinkedList isEmpty

List of usage examples for java.util LinkedList isEmpty

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:com.facebook.presto.accumulo.examples.TpcHClerkSearch.java

@Override
public int run(AccumuloConfig config, CommandLine cmd) throws Exception {
    String[] searchTerms = cmd.getOptionValues(CLERK_ID);

    ZooKeeperInstance inst = new ZooKeeperInstance(config.getInstance(), config.getZooKeepers());
    Connector conn = inst.getConnector(config.getUsername(), new PasswordToken(config.getPassword()));

    // Ensure both tables exists
    validateExists(conn, DATA_TABLE);/*w w w. j  a va2 s  . c o m*/
    validateExists(conn, INDEX_TABLE);

    long start = System.currentTimeMillis();

    // Create a scanner against the index table
    BatchScanner idxScanner = conn.createBatchScanner(INDEX_TABLE, new Authorizations(), 10);
    LinkedList<Range> searchRanges = new LinkedList<Range>();

    // Create a search Range from the command line args
    for (String searchTerm : searchTerms) {
        if (clerkRegex.matcher(searchTerm).matches()) {
            searchRanges.add(new Range(searchTerm));
        } else {
            throw new InvalidParameterException(
                    format("Search term %s does not match regex Clerk#[0-9]{9}", searchTerm));
        }
    }

    // Set the search ranges for our scanner
    idxScanner.setRanges(searchRanges);

    // A list to hold all of the order IDs
    LinkedList<Range> orderIds = new LinkedList<Range>();
    String orderId;

    // Process all of the records returned by the batch scanner
    for (Map.Entry<Key, Value> record : idxScanner) {
        // Get the order ID and add it to the list of order IDs
        orderIds.add(new Range(record.getKey().getColumnQualifier()));
    }

    // Close the batch scanner
    idxScanner.close();

    // If clerkIDs is empty, log a message and return 0
    if (orderIds.isEmpty()) {
        System.out.println("Found no orders with the given Clerk ID(s)");
        return 0;
    } else {
        System.out.println(format("Searching data table for %d orders", orderIds.size()));
    }

    // Initialize the batch scanner to scan the data table with
    // the previously found order IDs as the ranges
    BatchScanner dataScanner = conn.createBatchScanner(DATA_TABLE, new Authorizations(), 10);
    dataScanner.setRanges(orderIds);
    dataScanner.addScanIterator(new IteratorSetting(1, WholeRowIterator.class));

    Text row = new Text(); // The row ID
    Text colQual = new Text(); // The column qualifier of the current record

    Long orderkey = null;
    Long custkey = null;
    String orderstatus = null;
    Double totalprice = null;
    Date orderdate = null;
    String orderpriority = null;
    String clerk = null;
    Long shippriority = null;
    String comment = null;

    int numTweets = 0;
    // Process all of the records returned by the batch scanner
    for (Map.Entry<Key, Value> entry : dataScanner) {
        entry.getKey().getRow(row);
        orderkey = decode(Long.class, row.getBytes(), row.getLength());
        SortedMap<Key, Value> rowMap = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
        for (Map.Entry<Key, Value> record : rowMap.entrySet()) {
            // Get the column qualifier from the record's key
            record.getKey().getColumnQualifier(colQual);

            switch (colQual.toString()) {
            case CUSTKEY_STR:
                custkey = decode(Long.class, record.getValue().get());
                break;
            case ORDERSTATUS_STR:
                orderstatus = decode(String.class, record.getValue().get());
                break;
            case TOTALPRICE_STR:
                totalprice = decode(Double.class, record.getValue().get());
                break;
            case ORDERDATE_STR:
                orderdate = decode(Date.class, record.getValue().get());
                break;
            case ORDERPRIORITY_STR:
                orderpriority = decode(String.class, record.getValue().get());
                break;
            case CLERK_STR:
                clerk = decode(String.class, record.getValue().get());
                break;
            case SHIPPRIORITY_STR:
                shippriority = decode(Long.class, record.getValue().get());
                break;
            case COMMENT_STR:
                comment = decode(String.class, record.getValue().get());
                break;
            default:
                throw new RuntimeException("Unknown column qualifier " + colQual);
            }
        }

        ++numTweets;
        // Write the screen name and text to stdout
        System.out.println(format("%d|%d|%s|%f|%s|%s|%s|%d|%s", orderkey, custkey, orderstatus, totalprice,
                orderdate, orderpriority, clerk, shippriority, comment));

        custkey = null;
        shippriority = null;
        orderstatus = null;
        orderpriority = null;
        clerk = null;
        comment = null;
        totalprice = null;
        orderdate = null;
    }

    // Close the batch scanner
    dataScanner.close();

    long finish = System.currentTimeMillis();

    System.out.format("Found %d orders in %s ms\n", numTweets, (finish - start));
    return 0;
}

From source file:acromusashi.stream.component.rabbitmq.CachingConnectionFactory.java

private Channel getChannel(boolean transactional) {
    LinkedList<ChannelProxy> channelList = transactional ? this.cachedChannelsTransactional
            : this.cachedChannelsNonTransactional;
    Channel channel = null;/*  w w w . j a v a2 s.c  o  m*/
    synchronized (channelList) {
        if (!channelList.isEmpty()) {
            channel = channelList.removeFirst();
        }
    }
    if (channel != null) {
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("Found cached Rabbit Channel");
        }
    } else {
        channel = getCachedChannelProxy(channelList, transactional);
    }
    return channel;
}

From source file:com.android.utils.AccessibilityNodeInfoUtils.java

/**
 * Returns the result of applying a filter using breadth-first traversal.
 *
 * @param node The root node to traverse from.
 * @param filter The filter to satisfy./*  w  w  w .  j  a  va 2  s  . com*/
 * @return The first node reached via BFS traversal that satisfies the
 *         filter.
 */
public static AccessibilityNodeInfoCompat searchFromBfs(AccessibilityNodeInfoCompat node, NodeFilter filter) {
    if (node == null) {
        return null;
    }

    final LinkedList<AccessibilityNodeInfoCompat> queue = new LinkedList<>();
    Set<AccessibilityNodeInfoCompat> visitedNodes = new HashSet<>();

    queue.add(AccessibilityNodeInfoCompat.obtain(node));

    try {
        while (!queue.isEmpty()) {
            final AccessibilityNodeInfoCompat item = queue.removeFirst();
            visitedNodes.add(item);

            if (filter.accept(item)) {
                return item;
            }

            final int childCount = item.getChildCount();

            for (int i = 0; i < childCount; i++) {
                final AccessibilityNodeInfoCompat child = item.getChild(i);

                if (child != null && !visitedNodes.contains(child)) {
                    queue.addLast(child);
                }
            }
            item.recycle();
        }
    } finally {
        while (!queue.isEmpty()) {
            queue.removeFirst().recycle();
        }
    }

    return null;
}

From source file:it.cnr.icar.eric.client.admin.function.Cp.java

/**
 * Load the contents of baseDir into rp using pathname as base for
 * locators of loaded objects.//  ww  w .j  a  va2 s  .c  o  m
 *
 * @param baseDir  Directory in local file system from which to load
 * @param rp       Existing RegistryPackage to which to add
 */
protected void scanDir(File baseDir, RegistryPackage rootRP) throws Exception {
    ArrayList<RegistryObject> repositoryObjects = new ArrayList<RegistryObject>();

    LinkedList<DirInfo> dirInfoList = new LinkedList<DirInfo>();

    dirInfoList.add(new DirInfo(baseDir, rootRP));

    /*
     * Loop through the list of directories (and corresponding
     * RegistryPackages and pathnames).  Child directories of
     * curDir are added to the end of the list, so the list isn't
     * finished until all descendant directories have been
     * processed.
     */
    while (!dirInfoList.isEmpty()) {
        DirInfo curDirInfo = dirInfoList.removeFirst();
        File curDir = curDirInfo.getDir();
        RegistryPackage curRP = curDirInfo.getRegistryPackage();

        if (!curDir.exists()) {
            throw new AdminException(format(rb, "nonexistentLocalDir", new Object[] { curDir }));
        }

        if (!curDir.isDirectory()) {
            throw new AdminException(format(rb, "nondirectoryLocalDir", new Object[] { curDir }));
        }

        if (!curDir.canRead()) {
            throw new AdminException(format(rb, "unreadableLocalDir", new Object[] { curDir }));
        }

        File[] childFiles = curDir.listFiles();

        for (int i = 0; i < childFiles.length; i++) {
            String childName = childFiles[i].getName();

            boolean canInclude = checkIncludesExcludes(childName);

            RegistryObject childObject;

            if (!canInclude) {
                if (verbose || debug) {
                    context.printMessage(format(rb, "notIncluding", new Object[] { childFiles[i] }));
                }

                continue;
            }

            if (childFiles[i].isFile()) {
                if (verbose || debug) {
                    context.printMessage(format(rb, "including",
                            new Object[] { "ExtrinsicObject", childFiles[i], childName }));
                }

                childObject = context.getService().createExtrinsicObject(childFiles[i]);
            } else if (childFiles[i].isDirectory()) {
                if (verbose || debug) {
                    context.printMessage(format(rb, "including",
                            new Object[] { "RegistryPackage", childFiles[i], childName }));
                }

                childObject = context.getService().createRegistryPackage(childName);

                dirInfoList.addLast(new DirInfo(childFiles[i], (RegistryPackage) childObject));
            } else {
                childObject = null;
                throw new AdminException(format(rb, "notFileOrDir", new Object[] { childFiles[i] }));
            }

            if (curRP != null) {
                curRP.addRegistryObject(childObject);
            }

            repositoryObjects.add(childObject);
        }
    }

    if (!repositoryObjects.isEmpty()) {
        if (rootRP != null) {
            repositoryObjects.add(rootRP);
        }

        BulkResponse response = ((LifeCycleManagerImpl) context.getService().getLCM())
                .saveObjects(repositoryObjects, saveObjectsSlots);

        JAXRUtility.checkBulkResponse(response);
    }
}

From source file:com.epam.reportportal.apache.http.conn.ssl.AbstractVerifier.java

public final void verify(final String host, final String[] cns, final String[] subjectAlts,
        final boolean strictWithSubDomains) throws SSLException {

    // Build the list of names we're going to check.  Our DEFAULT and
    // STRICT implementations of the HostnameVerifier only use the
    // first CN provided.  All other CNs are ignored.
    // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
    final LinkedList<String> names = new LinkedList<String>();
    if (cns != null && cns.length > 0 && cns[0] != null) {
        names.add(cns[0]);//  ww  w. jav a  2s.  c o m
    }
    if (subjectAlts != null) {
        for (final String subjectAlt : subjectAlts) {
            if (subjectAlt != null) {
                names.add(subjectAlt);
            }
        }
    }

    if (names.isEmpty()) {
        final String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt";
        throw new SSLException(msg);
    }

    // StringBuilder for building the error message.
    final StringBuilder buf = new StringBuilder();

    // We're can be case-insensitive when comparing the host we used to
    // establish the socket to the hostname in the certificate.
    final String hostName = normaliseIPv6Address(host.trim().toLowerCase(Locale.US));
    boolean match = false;
    for (final Iterator<String> it = names.iterator(); it.hasNext();) {
        // Don't trim the CN, though!
        String cn = it.next();
        cn = cn.toLowerCase(Locale.US);
        // Store CN in StringBuilder in case we need to report an error.
        buf.append(" <");
        buf.append(cn);
        buf.append('>');
        if (it.hasNext()) {
            buf.append(" OR");
        }

        // The CN better have at least two dots if it wants wildcard
        // action.  It also can't be [*.co.uk] or [*.co.jp] or
        // [*.org.uk], etc...
        final String parts[] = cn.split("\\.");
        final boolean doWildcard = parts.length >= 3 && parts[0].endsWith("*") && validCountryWildcard(cn)
                && !isIPAddress(host);

        if (doWildcard) {
            final String firstpart = parts[0];
            if (firstpart.length() > 1) { // e.g. server*
                final String prefix = firstpart.substring(0, firstpart.length() - 1); // e.g. server
                final String suffix = cn.substring(firstpart.length()); // skip wildcard part from cn
                final String hostSuffix = hostName.substring(prefix.length()); // skip wildcard part from host
                match = hostName.startsWith(prefix) && hostSuffix.endsWith(suffix);
            } else {
                match = hostName.endsWith(cn.substring(1));
            }
            if (match && strictWithSubDomains) {
                // If we're in strict mode, then [*.foo.com] is not
                // allowed to match [a.b.foo.com]
                match = countDots(hostName) == countDots(cn);
            }
        } else {
            match = hostName.equals(normaliseIPv6Address(cn));
        }
        if (match) {
            break;
        }
    }
    if (!match) {
        throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf);
    }
}

From source file:nl.tue.bimserver.citygml.CityGmlSerializer.java

private <T extends AbstractCityObject> T buildBoundarySurface(IfcProduct ifcProduct, T cityObject)
        throws SerializerException {
    setName(cityObject.getName(), ifcProduct.getName());
    setGlobalId(cityObject, ifcProduct);

    MultiSurface multiSurface = gml.createMultiSurface();

    {/*from w w  w .  j  a  v  a  2  s.c  o m*/
        CompositeSurface compositeSurface = gml.createCompositeSurface();
        setGeometry(compositeSurface, ifcProduct);
        materialManager.assign(compositeSurface, ifcProduct);
        multiSurface.addSurfaceMember(gml.createSurfaceProperty(compositeSurface));
    }

    LinkedList<IfcObjectDefinition> decompose = new LinkedList<IfcObjectDefinition>(
            Collections.singletonList(ifcProduct));
    while (!decompose.isEmpty()) {
        for (IfcRelDecomposes ifcRelDecomposes : decompose.removeFirst().getIsDecomposedBy()) {
            for (IfcObjectDefinition ifcObjectDef : ifcRelDecomposes.getRelatedObjects()) {
                CompositeSurface compositeSurface = gml.createCompositeSurface();
                setGeometry(compositeSurface, ifcObjectDef);
                materialManager.assign(compositeSurface, ifcObjectDef);
                multiSurface.addSurfaceMember(gml.createSurfaceProperty(compositeSurface));
                decompose.add(ifcObjectDef);
            }
        }
    }

    MultiSurfaceProperty multiSurfaceProperty = gml.createMultiSurfaceProperty(multiSurface);
    try {
        if (PropertyUtils.isWriteable(cityObject, "lod4MultiSurface")) {
            PropertyUtils.setProperty(cityObject, "lod4MultiSurface", multiSurfaceProperty);
        } else {
            PropertyUtils.setProperty(cityObject, "lod4Geometry", multiSurfaceProperty);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return cityObject;
}

From source file:annis.gui.resultview.ResultViewPanel.java

@Override
public boolean onCompononentLoaded(AbstractClientConnector source) {
    if (source != null) {
        if (projectQueue != null && currentQuery != null) {
            LinkedList<SaltProject> subgraphs = new LinkedList<>();
            SaltProject p;/*from  w ww  .j a va  2s . c  om*/
            while ((p = projectQueue.poll()) != null) {
                log.debug("Polling queue for SaltProject graph");
                subgraphs.add(p);
            }
            if (subgraphs.isEmpty()) {
                log.debug("no SaltProject graph in queue");
                return false;
            }

            log.debug("taken {} SaltProject graph(s) from queue", subgraphs.size());
            addQueryResult(currentQuery, subgraphs);
            return true;

        }
    }

    return true;
}

From source file:org.geometerplus.android.fbreader.BookmarkFragmentActivity.java

@Override
protected void onNewIntent(Intent intent) {
    OrientationUtil.setOrientation(this, intent);

    if (!Intent.ACTION_SEARCH.equals(intent.getAction())) {
        return;//from   w  w  w.  j av a  2 s . com
    }
    String pattern = intent.getStringExtra(SearchManager.QUERY);
    myBookmarkSearchPatternOption.setValue(pattern);

    final LinkedList<Bookmark> bookmarks = new LinkedList<Bookmark>();
    pattern = pattern.toLowerCase();
    for (Bookmark b : myAllBooksAdapter.bookmarks()) {
        if (MiscUtil.matchesIgnoreCase(b.getText(), pattern)) {
            bookmarks.add(b);
        }
    }
    if (!bookmarks.isEmpty()) {
        showSearchResultsTab(bookmarks);
    } else {
        UIUtil.showErrorMessage(this, "quoteNotFound");
    }
}

From source file:org.overture.codegen.vdm2java.JavaFormat.java

public String formatInterfaces(AClassDeclCG classDecl) {
    LinkedList<AInterfaceDeclCG> interfaces = classDecl.getInterfaces();

    if (interfaces == null || interfaces.isEmpty()) {
        return "";
    }/*from  w w  w .j a va  2s.c  o  m*/

    String implementsClause = "implements";

    implementsClause += " " + interfaces.get(0).getName();

    for (int i = 1; i < interfaces.size(); i++) {
        implementsClause += ", " + interfaces.get(i).getName();
    }

    return implementsClause;
}

From source file:net.joaopeixoto.geode.server.functions.PatternFunctions.java

/**
 * Replace here with your favorite algorithm
 *///from w w  w .  jav  a2s . c o  m
@GemfireFunction
public DistanceResult distance(List<Metric> metrics) {
    Assert.notEmpty(metrics);
    Metric first = metrics.get(0);

    LinkedList<Metric> currentWindow = new LinkedList<>();
    LinkedList<Metric> matchedWindow = new LinkedList<>();
    double minDistance = THRESHOLD;
    int matchCount = 0;

    log.debug("Checking for patterns comparing with {}", metrics);

    List<Metric> localValues = new ArrayList<>(metricRegion.values());

    /**
     * Ensure the local values are ordered. {@link Region#values()} does not guarantee it.
     */
    Collections.sort(localValues);
    for (Metric metric : localValues) {

        // Ignore overlapping points or noise
        if (metric.getTimestamp() >= first.getTimestamp() || metric.getValue().compareTo(BigDecimal.TEN) < 1) {
            if (!currentWindow.isEmpty()) {
                currentWindow.pop();
            }
            continue;
        }

        currentWindow.add(metric);
        if (currentWindow.size() > 13) {
            currentWindow.pop();
        }

        /**
         * We only compare windows the same size (for now)
         */
        if (currentWindow.size() == 13) {

            TimeWarpInfo compare = DTW.compare(metricToSeries(currentWindow), metricToSeries(metrics),
                    Distances.EUCLIDEAN_DISTANCE);
            if (compare.getDistance() <= 1D) {
                matchCount++;
                matchedWindow = new LinkedList<>(currentWindow);
            }
        }
    }

    if (matchCount > 0) {
        return new DistanceResult(matchedWindow, minDistance, matchCount);
    }
    return null;
}