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:org.hyperic.hq.product.util.PluginDumper.java

private void flushEvents(LinkedList events, String name) {
    if (events.isEmpty()) {
        return;//w ww .  jav  a  2 s.co m
    }

    System.out.println(name + " events...");
    for (Iterator i = events.iterator(); i.hasNext();) {
        TrackEvent event = (TrackEvent) i.next();
        System.out.println(
                "[" + new Date(event.getTime()) + "] " + "(" + event.getSource() + ") " + event.getMessage());
    }
}

From source file:org.lambdamatic.analyzer.LambdaExpressionAnalyzer.java

/**
 * Simplify the given {@link Statement} keeping all branches that end with a "return 1" node, and
 * combining the remaining ones in an {@link CompoundExpression}.
 * //from  w  w  w .  j  a v a2s. c o m
 * @param statement the statement to thin out
 * @return the resulting "thined out" {@link Statement}
 */
private static Statement thinOut(final Statement statement) {
    LOGGER.debug("About to simplify \n\t{}", NodeUtils.prettyPrint(statement));
    if (statement.getStatementType() == StatementType.EXPRESSION_STMT) {
        return statement;
    } else {
        // find branches that end with 'return 1'
        final ReturnTruePathFilter filter = new ReturnTruePathFilter();
        statement.accept(filter);
        final List<ReturnStatement> returnStmts = filter.getReturnStmts();
        final List<Expression> expressions = new ArrayList<>();
        for (ReturnStatement returnStmt : returnStmts) {
            final LinkedList<Expression> relevantExpressions = new LinkedList<>();
            // current node being evaluated
            Statement currentStmt = returnStmt;
            // previous node evaluated, because it is important to remember
            // the path that was taken (in case of ConditionalStatements)
            Statement previousStmt = null;
            while (currentStmt != null) {
                switch (currentStmt.getStatementType()) {
                case CONTROL_FLOW_STMT:
                    final ControlFlowStatement controlFlowStatement = (ControlFlowStatement) currentStmt;
                    final Expression controlFlowExpression = controlFlowStatement.getControlFlowExpression();
                    // if we come from the "eval true" path on this
                    // condition
                    if (controlFlowStatement.getThenStatements().contains(previousStmt)) {
                        relevantExpressions.add(0, controlFlowExpression);
                    } else {
                        relevantExpressions.add(0, controlFlowExpression.inverse());
                    }
                    break;
                case RETURN_STMT:
                    final Expression returnExpression = ((ReturnStatement) currentStmt).getExpression();
                    if (returnExpression.getExpressionType() == ExpressionType.METHOD_INVOCATION) {
                        relevantExpressions.add(0, returnExpression);
                    }
                    break;
                default:
                    LOGGER.trace("Ignoring node '{}'", currentStmt);
                    break;
                }
                previousStmt = currentStmt;
                currentStmt = currentStmt.getParent();
            }
            if (relevantExpressions.size() > 1) {
                expressions.add(new CompoundExpression(CompoundExpressionOperator.CONDITIONAL_AND,
                        relevantExpressions));
            } else if (!relevantExpressions.isEmpty()) {
                expressions.add(relevantExpressions.getFirst());
            }

        }
        if (expressions.isEmpty()) {
            return statement;
        }
        final Statement result = (expressions.size() > 1)
                ? new ReturnStatement(
                        new CompoundExpression(CompoundExpressionOperator.CONDITIONAL_OR, expressions))
                : new ReturnStatement(expressions.get(0));
        LOGGER.debug("Thinned out expression: {}", result.toString());
        return result;
    }
}

From source file:net.timewalker.ffmq4.storage.data.impl.journal.BlockBasedDataStoreJournal.java

private void recycleUnusedJournalFiles() throws JournalException {
    LinkedList<JournalFile> unusedJournalFiles = null;

    // Look for unused journal files
    synchronized (journalFiles) {
        while (journalFiles.size() > 0) {
            JournalFile journalFile = journalFiles.getFirst();
            if (journalFile.isComplete() && journalFile.getLastTransactionId() < lastStoreTransactionId) {
                if (unusedJournalFiles == null)
                    unusedJournalFiles = new LinkedList<>();
                unusedJournalFiles.addLast(journalFile);

                journalFiles.removeFirst(); // Remove from list
            } else
                break;
        }//from  w ww.  j a  v a2s.  c om
    }

    // Recycle unused journal files
    if (unusedJournalFiles != null) {
        while (!unusedJournalFiles.isEmpty()) {
            JournalFile journalFile = unusedJournalFiles.removeFirst();

            if (keepJournalFiles)
                journalFile.close();
            else {
                log.debug("[" + baseName + "] Recycling unused journal file : " + journalFile);
                File recycledFile = journalFile.closeAndRecycle();
                synchronized (recycledJournalFiles) {
                    recycledJournalFiles.addLast(recycledFile);
                }
            }
        }
    }
}

From source file:org.squashtest.tm.service.internal.batchimport.Model.java

/**
 * returns all parameters available to a test case. This includes every
 * ParameterTarget from the test cases being called directly or indirectly
 * by this test case, not just the one owner by the test case (unlike
 * getOwnParameters). Parameters from downstream test cases will be included
 * iif they are inherited in some ways.//from w  ww.  ja  v a2s. c o  m
 */
public Collection<ParameterTarget> getAllParameters(TestCaseTarget testCase) {

    if (!callGraph.knowsNode(testCase)) {
        initCallGraph(testCase);
    }

    Collection<ParameterTarget> result = new HashSet<>();
    LinkedList<Node> processing = new LinkedList<>();
    Set<Node> processed = new HashSet<>();

    processing.add(callGraph.getNode(testCase));

    while (!processing.isEmpty()) {
        Node current = processing.pop();
        result.addAll(getOwnParameters(current.getKey()));

        // modification patron
        for (Node child : current.getOutbounds()) {

            List<InternalStepModel> steps = testCaseStepsByTarget.get(current.getKey());
            extractParametersFromSteps(processing, processed, child, steps);
            processed.add(current);
        }

    }

    return result;

}

From source file:io.apptik.widget.MultiSlider.java

private Thumb getMostMovable(LinkedList<Thumb> thumbs, MotionEvent event) {
    Thumb res = null;// w  w w .  j a  v  a 2  s  .  c om
    int maxChange = 0;
    if (thumbs != null && !thumbs.isEmpty()) {

        if (thumbs.getFirst().getValue() == getValue(event, thumbs.getFirst()))
            return null;

        for (Thumb thumb : thumbs) {
            int optValue = (getValue(event, thumbs.getFirst()) > thumb.getValue()) ? mScaleMax : mScaleMin;
            int currChange = Math.abs(thumb.getValue() - optThumbValue(thumb, optValue));
            if (currChange > maxChange) {
                maxChange = currChange;
                res = thumb;
            }
        }
    }
    return res;
}

From source file:org.fusesource.mop.support.MethodCommandDefinition.java

@Override
public void executeCommand(MOP mop, LinkedList<String> argList) throws Exception {
    // lets inject fields
    for (Class<? extends Object> beanType = bean.getClass(); beanType != Object.class; beanType = beanType
            .getSuperclass()) {//from   ww w .  ja  v a 2  s . com
        Field[] fields = beanType.getDeclaredFields();
        for (Field field : fields) {
            Lookup lookup = field.getAnnotation(Lookup.class);
            if (lookup != null) {
                Class<?> type = field.getType();
                Object value = mop.getContainer().lookup(type);
                if (value != null) {
                    field.setAccessible(true);
                    field.set(bean, value);
                }
            }
        }
    }

    Class<?>[] paramTypes = method.getParameterTypes();
    int size = paramTypes.length;
    Object[] args = new Object[size];
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();

    for (int i = 0; i < size; i++) {
        Class<?> paramType = paramTypes[i];
        if (MOP.class.isAssignableFrom(paramType)) {
            args[i] = mop;
        } else if (Iterable.class.isAssignableFrom(paramType)) {
            // lets assume its the command arguments
            args[i] = argList;
        } else {
            if (argList.isEmpty()) {
                // lets look and see if we should allow a null
                Annotation[] annotations = parameterAnnotations[i];
                if (isOptionalValue(annotations)) {
                    continue;
                }
                // TODO we need to find the name of the parameter to log better!
                throw new Exception("missing argument!");
            }

            // now lets extract the actual arguments
            if (Artifacts.class.isAssignableFrom(paramType)) {
                args[i] = mop.getArtifacts(argList);
            } else if (paramType == File.class) {
                args[i] = new File(argList.removeFirst());
            } else if (paramType == String.class) {
                args[i] = argList.removeFirst();
            } else {
                throw new Exception("Unable to inject type " + paramType.getName() + " from arguments "
                        + argList + " for method " + method);
            }
        }

    }

    if (bean instanceof ConfiguresMop) {
        ConfiguresMop configuresMop = (ConfiguresMop) bean;
        configuresMop.configure(mop);
    }
    try {
        method.invoke(bean, args);
    } catch (Exception e) {
        LOG.error("Failed to invoke " + method + " with args " + Arrays.asList(args) + " due to: " + e, e);
        throw e;
    }
}

From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java

private void initDeviceLists(ShareMetaData smd)
        throws SQLException, InitializaionException, SignatureException, DeviceListException {

    smd.deviceLists = new TreeMap<PublicKey, DeviceList>(Utils.PK_COMPARATOR);

    Connection con = null;//from w  w w  .j a v a  2 s .  c o  m
    SharePartList spl = smd.getSharePartList();
    if (spl != null) {
        Iterator<String> it = spl.getAliases();

        while (it.hasNext()) {
            String alias = (String) it.next();
            PublicKey pKey = spl.getPublicKey(alias);
            String fingerprint = DigestUtils.sha256Hex(pKey.getEncoded());
            String url = dbURL + fingerprint + ".db";
            try {
                con = DriverManager.getConnection(url, p);
                Statement s = con.createStatement();
                ResultSet rs = s.executeQuery(DEVICELIST_HAS_TABLES);
                if (rs.next() && DEVICELIST_NUM_TABLES == rs.getInt(1)) {
                    rs.close();
                    s.close();
                    logger.debug("Tables exist, loading devicelist for user " + alias);
                    loadDeviceList(con, smd, pKey);
                } else {
                    rs.close();
                    logger.debug("new Volume, creating tables for devicelist for user " + alias);
                    createDLTables(s);
                    s.close();
                }
            } catch (SQLException e) {
                logger.error("Error reading device list DB", e);
                SQLiteErrorCode code = SQLiteErrorCode.getErrorCode(e.getErrorCode());
                if (code.equals(SQLiteErrorCode.SQLITE_NOTADB) || code.equals(SQLiteErrorCode.SQLITE_CORRUPT)) {
                    // TODO: corrupt DB, consider deleting .db file
                    logger.warn("DB was corrupt, URL: " + dbURL);
                }
                continue;
            } finally {
                if (con != null) {
                    try {
                        con.close();
                    } catch (SQLException e) {
                        logger.warn("Could not close DataBase Connection", e);
                    }
                }
            }
        }

        // check devicelist signatures
        it = spl.getAliases();
        LinkedList<PublicKey> corruptDeviceList = new LinkedList<>();
        while (it.hasNext()) {
            String alias = (String) it.next();
            PublicKey pKey = spl.getPublicKey(alias);
            DeviceList list = smd.deviceLists.get(pKey);
            try {
                verifyDeviceList(smd, pKey, list);
            } catch (Exception e) {
                logger.warn("Could not verifiy device list of user" + alias, e);
                corruptDeviceList.add(pKey);
                if (list != null) {
                    for (PublicKey deviceKey : list.getPublicKeys()) {
                        smd.removeObfuscationKey(deviceKey);
                        smd.getShareKeys().removeDevice(deviceKey);
                    }
                }
            }
        }
        if (!corruptDeviceList.isEmpty()) {
            throw new DeviceListException("Could not verify DeviceList(s)!", corruptDeviceList);
        }
    }
}

From source file:org.apache.tapestry.util.AdaptorRegistry.java

/**
 * Searches the registration Map for a match, based on inheritance.
 *
 * <p>Searches class inheritance first, then interfaces (in a rather vague order).
 * Really should match the order from the JVM spec.
 *
 * <p>There's a degenerate case where we may check the same interface more than once:
 * <ul>//from  ww  w .j a  v a2 s .c o m
 * <li>Two interfaces, I1 and I2
 * <li>Two classes, C1 and C2
 * <li>I2 extends I1
 * <li>C2 extends C1
 * <li>C1 implements I1
 * <li>C2 implements I2
 * <li>The search will be: C2, C1, I2, I1, I1
 * <li>I1 is searched twice, because C1 implements it, and I2 extends it
 * <li>There are other such cases, but none of them cause infinite loops
 * and most are rare (we could guard against it, but its relatively expensive).
 * <li>Multiple checks only occur if we don't find a registration
 * </ul>
 *
 *  <p>
 *  This method is only called from a synchronized block, so it is
 *  implicitly synchronized.
 * 
 **/

private Object searchForAdaptor(Class subjectClass) {
    LinkedList queue = null;
    Object result = null;

    if (LOG.isDebugEnabled())
        LOG.debug("Searching for adaptor for class " + Tapestry.getClassName(subjectClass));

    // Step one: work up through the class inheritance.

    Class searchClass = subjectClass;

    // Primitive types have null, not Object, as their parent
    // class.

    while (searchClass != Object.class && searchClass != null) {
        result = registrations.get(searchClass);
        if (result != null)
            return result;

        // Not an exact match.  If the search class
        // implements any interfaces, add them to the queue.

        Class[] interfaces = searchClass.getInterfaces();
        int length = interfaces.length;

        if (queue == null && length > 0)
            queue = new LinkedList();

        for (int i = 0; i < length; i++)
            queue.addLast(interfaces[i]);

        // Advance up to the next superclass

        searchClass = getSuperclass(searchClass);

    }

    // Ok, the easy part failed, lets start searching
    // interfaces.

    if (queue != null) {
        while (!queue.isEmpty()) {
            searchClass = (Class) queue.removeFirst();

            result = registrations.get(searchClass);
            if (result != null)
                return result;

            // Interfaces can extend other interfaces; add them
            // to the queue.

            Class[] interfaces = searchClass.getInterfaces();
            int length = interfaces.length;

            for (int i = 0; i < length; i++)
                queue.addLast(interfaces[i]);
        }
    }

    // Not a match on interface; our last gasp is to check
    // for a registration for java.lang.Object

    result = registrations.get(Object.class);
    if (result != null)
        return result;

    // No match?  That's rare ... and an error.

    throw new IllegalArgumentException(
            Tapestry.format("AdaptorRegistry.adaptor-not-found", Tapestry.getClassName(subjectClass)));
}

From source file:org.powertac.customer.model.LiftTruck.java

/**
 * Converts a list of Strings to a sorted list of Shifts. Entries in the
 * list represent pairs of (start, duration) values. 
 *//*from   ww  w  . ja  v  a 2s. c o m*/
@ConfigurableValue(valueType = "List", dump = false, description = "shift spec [block, shift, ..., block, shift, ...]")
public void setShiftData(List<String> data) {
    int blk = 0;
    int shf = 1;
    int state = shf;

    LinkedList<String> tokens = new LinkedList<String>(data);
    ArrayList<Integer> blockData = new ArrayList<Integer>();
    ArrayList<Integer> shiftData = new ArrayList<Integer>();
    while (!(tokens.isEmpty())) {
        String token = tokens.remove();
        if (token.equals("block")) {
            // finish shift, switch to block
            if (!shiftData.isEmpty()) {
                finishShift(blockData, shiftData);
                shiftData.clear();
            }
            blockData.clear();
            state = blk;
        } else if (token.equals("shift")) {
            // finish block or previous shift, switch to shift
            if (!shiftData.isEmpty()) {
                finishShift(blockData, shiftData);
                shiftData.clear();
            }
            state = shf;
        } else { // collect numbers into correct list
            try {
                if (state == shf)
                    shiftData.add(Integer.parseInt(token));
                else if (state == blk)
                    blockData.add(Integer.parseInt(token));
            } catch (NumberFormatException nfe) {
                log.error("Config error for " + getName() + ": bad numeric token " + token);
            }
        }
    }
    // finish up last shift
    if (!shiftData.isEmpty()) {
        finishShift(blockData, shiftData);
    }
}

From source file:org.alfresco.repo.rendition.StandardRenditionLocationResolverImpl.java

private RenditionLocationImpl findOrCreateTemplatedPath(NodeRef sourceNode, String path, NodeRef companyHome) {
    if (log.isDebugEnabled()) {
        StringBuilder msg = new StringBuilder();
        msg.append("FindOrCreateTemplatedPath for ").append(sourceNode).append(", ").append(path);
        log.debug(msg.toString());//from w w  w. j a  v  a 2s  .  co m
    }

    NodeService nodeService = serviceRegistry.getNodeService();

    List<String> pathElements = Arrays.asList(path.split("/"));
    LinkedList<String> folderElements = new LinkedList<String>(pathElements);

    // We need to strip out any empty strings within the path elements.
    // prior to passing this path to the fileFolderService for creation.
    // e.g. "//foo//bar///item.txt" would cause an exception.
    folderElements.removeAll(Arrays.asList(new String[] { "" }));

    // Remove 'Company Home' if it is at the start of the path.
    Serializable companyHomeName = nodeService.getProperty(companyHome, ContentModel.PROP_NAME);
    if (folderElements.getFirst().equals(companyHomeName)) {
        folderElements.removeFirst();
    }

    String fileName = folderElements.removeLast();
    if (fileName == null || fileName.length() == 0) {
        StringBuilder msg = new StringBuilder();
        msg.append("The path must include a valid filename! Path: ").append(path);
        if (log.isDebugEnabled()) {
            log.debug(msg.toString());
        }
        throw new RenditionServiceException(msg.toString());
    }

    FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
    NodeRef parent = companyHome;
    if (!folderElements.isEmpty()) {
        FileInfo parentInfo = FileFolderUtil.makeFolders(fileFolderService, companyHome, folderElements,
                ContentModel.TYPE_FOLDER);
        parent = parentInfo.getNodeRef();
    }

    if (log.isDebugEnabled()) {
        log.debug("folderElements: " + folderElements);
        log.debug("parent: " + parent);
        log.debug("   " + nodeService.getType(parent) + " " + nodeService.getPath(parent));
        log.debug("fileName: " + fileName);
    }

    NodeRef child = fileFolderService.searchSimple(parent, fileName);

    if (log.isDebugEnabled()) {
        StringBuilder msg = new StringBuilder();
        msg.append("RenditionLocation parent=").append(parent).append(", child=").append(child)
                .append(", fileName=").append(fileName);
        log.debug(msg.toString());

        if (child != null) {
            log.debug("child path = " + nodeService.getPath(child));
        }
    }
    return new RenditionLocationImpl(parent, child, fileName);
}