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:org.dcm4chee.archive.conf.defaults.DeepEquals.java

/**
 * Deeply compare two Collections that must be same length and in same order.
 * @param dualKey collections// ww w . j av  a2 s.co m
 * @param stack add items to compare to the Stack (Stack versus recursion)
 * @param visited Set of objects already compared (prevents cycles)
 * value of 'true' indicates that the Collections may be equal, and the sets
 * items will be added to the Stack for further comparison.
 */
private static boolean compareOrderedCollection(DualKey dualKey, LinkedList stack, Set visited) {
    Collection col1 = (Collection) dualKey._key1;
    Collection col2 = (Collection) dualKey._key2;

    // Same instance check already performed...

    if (col1.size() != col2.size()) {
        return false;
    }

    // try sorting
    if (col1 instanceof List) {

        if (!col1.isEmpty()) {
            Object el = ((List) col1).get(0);

            if (el instanceof Comparable) {

                Collections.sort((List) col1);
                Collections.sort((List) col1);

            }
        }

    }

    Iterator i1 = col1.iterator();
    Iterator i2 = col2.iterator();

    int i = 0;

    while (i1.hasNext()) {
        DualKey dk = new DualKey(i1.next(), i2.next(), Integer.toString(i), dualKey);
        if (!visited.contains(dk)) { // push contents for further comparison
            stack.addFirst(dk);
        }
    }
    return true;
}

From source file:eu.nerdz.api.impl.fastreverse.messages.FastReverseConversationHandler.java

/**
 * This is the only method that needs of being overloaded, because it does all message fetching.
 * {@inheritDoc}/*from  www  .  ja  v  a  2  s.c  om*/
 */
@Override
protected Pair<List<Message>, Boolean> getMessagesAndCheck(Conversation conversation, int start, int howMany)
        throws IOException, HttpException, ContentException {

    if (howMany > 30) {
        howMany = 30;
    }

    if (start == 0 && howMany == 1 && conversation instanceof FastReverseConversation) { //FastReverseConversations contain the content of the last message - so we take this fast path.

        Pair<String, Boolean> lastInfo = ((FastReverseConversation) conversation).getLastMessageInfo();

        List<Message> lastMessage = new ArrayList<Message>(1);
        lastMessage.add(new FastReverseMessage(conversation, this.mUserInfo, conversation.getLastDate(),
                lastInfo.getLeft(), lastInfo.getRight(), false));

        return new ImmutablePair<List<Message>, Boolean>(lastMessage, false);
    }

    String response = this.mMessenger.get("/fastfetch.json.php?action=messages&otherid="
            + conversation.getOtherID() + "&start=" + start + "&limit=" + (howMany + 1));

    try {

        JSONObject errorObj = new JSONObject(response); //if this raises an exception, it's not an error response
        throw new ContentException(FastReverseErrCode.fromCode(errorObj.getInt("error")).toString());

    } catch (JSONException e) {

        try {

            JSONArray jsonResponse = new JSONArray(response);

            int length = jsonResponse.length();

            boolean hasMore = length > howMany; //if howMany is n, previously i've tried to fetch n + 1; if the number of elements fetched is really n + 1 this means that there are more messages.

            length = hasMore ? howMany : length;

            LinkedList<Message> conversationList = new LinkedList<Message>();

            for (int i = 0; i < length; ++i) {

                JSONObject conversationJson = jsonResponse.getJSONObject(i);

                boolean received = !conversationJson.getBoolean("sent");

                conversationList.addFirst(new FastReverseMessage(conversation, this.mUserInfo,
                        new Date(conversationJson.getLong("timestamp") * 1000L),
                        FastReverseConversationHandler.replaceBbcode(conversationJson.getString("message")),
                        received, conversationJson.getBoolean("read")));
            }

            return new ImmutablePair<List<Message>, Boolean>(conversationList, hasMore);
        } catch (JSONException e1) {

            e1.printStackTrace();

            throw new ContentException("Invalid json response from FastFetch");

        }
    }

}

From source file:org.nightlabs.base.ui.exceptionhandler.ExceptionHandlerRegistry.java

/**
 * Finds registered ExceptionHandlers. Moves up the class hierarchy for the
 * passed exception itself and all its nested cause exceptions to find
 * a handler for the specific class.//  ww  w.j  a  v  a 2s  .  c  o m
 * <p>
 * Note, that it starts at the root-cause and works its way up the wrapped exceptions.
 * </p>
 *
 * @param exception the exception thrown and in need to be handled.
 * @param skipItems all those items that should be ignored (usually, because they already have their handlers being triggered and their handlers returned false indicating that they don't want to handle the exception)
 * @return <code>null</code> if no handler could be found or an instance of {@link ExceptionHandlerSearchResult} containing the required information for triggering the handler.
 */
protected ExceptionHandlerSearchResult searchHandler(Throwable exception,
        Set<ExceptionHandlerRegistryItem> skipItems) {
    // make sure the registrations where made
    checkProcessing();

    // Build a stack of causes with the root cause being the first and the wrappers following in order of wrapping.
    // This is important, because if the priority of 2 handlers is the same (or it's the same handler), then
    // the handler closest to the root-cause is used and the triggerException is the one closest to the root.
    LinkedList<Throwable> causeStack = new LinkedList<Throwable>();
    {
        Throwable x = exception;
        while (x != null) {
            causeStack.addFirst(x);
            x = ExceptionUtils.getCause(x);
        }
    }

    // now iterate the causes and search for handler with highest logical (lowest numerical) priority
    ExceptionHandlerSearchResult result = null;
    ExceptionHandlerRegistryItem bestItem = null;
    for (Iterator<Throwable> itCause = causeStack.iterator(); itCause.hasNext();) {
        Throwable cause = itCause.next();
        Class<?> searchClass = cause.getClass();

        ExceptionHandlerRegistryItem item = getExceptionHandlerRegistryItem(searchClass);
        if (item != null && skipItems.contains(item))
            item = null;

        // If there is no item found or the item is skipped, we step up the class hierarchy of the 'cause' to find
        // a suitable item.
        while (item == null && !Throwable.class.equals(searchClass)) {
            searchClass = searchClass.getSuperclass();
            item = getExceptionHandlerRegistryItem(searchClass);

            // If there is no more wrapper-exception (i.e. itCause has no next element) and the found item is to be skipped,
            // we continue going up the class hierarchy. This should end in the worst case with the default exception handler
            // being used. But theoretically (if there is no default), this method might return null.
            // If we have further wrapper-exceptions, we do not go up the hierarchy, because the skipped handler probably was the right
            // one already and it obviously decided to skip this cause. I'm not completely sure yet, though, whether this strategy is the
            // best. Marco.
            //            if (item != null && !itCause.hasNext() && skipItems.contains(item)) 
            //               item = null;
            // hmmm... if a handler decided to ignore, we should probably better first stay at the same cause, climbing up the class
            // hierarchy, because this behaviour seems to make more sense. If the default handler is found, it has a very low
            // logical priority anyway, so that a more specific handler (having a higher logical priority) for a wrapping exception
            // will be chosen instead anyway. Marco.
            if (item != null && skipItems.contains(item))
                item = null;
        }

        if (item == null)
            continue;

        if (skipItems.contains(item))
            continue;

        if (bestItem == null) {
            bestItem = item;
            result = new ExceptionHandlerSearchResult();
            result.setExceptionHandlerRegistryItem(bestItem);
            result.setTriggerException(cause);
        } else if (bestItem.getPriority() > item.getPriority()) {
            bestItem = item;
            result.setExceptionHandlerRegistryItem(bestItem);
            result.setTriggerException(cause);
        }
    }

    return result;
}

From source file:org.dspace.app.webui.cris.controller.admin.FormAdministrationDOController.java

@Override
protected Object formBackingObject(HttpServletRequest request) throws Exception {
    String mode = request.getParameter("mode");
    String paramSort = request.getParameter("sort");
    String paramPage = request.getParameter("page");
    String paramDir = request.getParameter("dir");
    String paramOldPage = request.getParameter("oldpage");

    if (paramOldPage != null
            && (paramOldPage.equals(paramPage) || (Integer.parseInt(paramOldPage) == 1 && paramPage == null))) {
        String message = request.getParameter("message");
        request.setAttribute("message", message);
    }/*from www.  j a va 2 s  .c o m*/

    String shortName = Utils.getAdminSpecificPath(request, null);

    DynamicObjectType typo = applicationService.findTypoByShortName(DynamicObjectType.class, shortName);

    String sort = paramSort != null ? paramSort : "id";
    String dir = paramDir != null ? paramDir : "asc";
    int page = paramPage != null ? Integer.parseInt(paramPage) : 1;
    long count = applicationService.countResearchObjectByType(typo);
    Integer pagesize = Integer.parseInt(ConfigurationManager.getProperty(CrisConstants.CFG_MODULE,
            OTHERRESEARCHOBJECT_ADMINISTRATION_TABLE_PAGESIZE));

    //mode position only when administrator click on direct link on RP page  
    Integer id = null;
    if (mode != null && mode.equals("position") && paramPage == null && paramSort == null) {
        String id_s = request.getParameter("id");
        id = Integer.parseInt(id_s);
        page = id / pagesize + 1;
    }

    List<ResearchObject> researchers = applicationService.getResearchObjectPaginateListByType(typo, sort,
            "desc".equals(dir), page, pagesize);
    LinkedList<DynamicObjectDTO> objectList = new LinkedList<DynamicObjectDTO>();
    for (ResearchObject r : researchers) {
        DynamicObjectDTO rpd = new DynamicObjectDTO();
        rpd.setId(r.getId());
        rpd.setSourceID(r.getSourceID());
        rpd.setUuid(r.getUuid());
        rpd.setStatus(r.getStatus());
        rpd.setName(r.getName());
        rpd.setDynamicObject(r);
        if ((r.getId()).equals(id)) {
            objectList.addFirst(rpd);
        } else {
            objectList.add(rpd);
        }
    }

    DODisplayTagData displayList = new DODisplayTagData(count, objectList, sort, dir, page, pagesize);

    return displayList;

}

From source file:org.springframework.core.convert.support.GenericConversionService.java

private void addInterfaceHierarchy(Class<?> ifc, LinkedList<Class<?>> classQueue) {
    classQueue.addFirst(ifc);
    for (Class<?> inheritedIfc : ifc.getInterfaces()) {
        addInterfaceHierarchy(inheritedIfc, classQueue);
    }//from   ww  w.  jav a  2 s  . co m
}

From source file:org.apache.metron.profiler.client.window.WindowProcessor.java

/**
 * Read the specifier params off the stack in FIFO order until we get to the specifier marker.  Now we can
 * construct the specifier, which is a Function which constructs a Selector Predicate based on the args
 * passed to the selector e.g. holidays:us:nyc would have 2 args us and nyc.
 *
 * @param ctx// w  w w. jav  a  2s  . c o m
 */
@Override
public void exitSpecifier(WindowParser.SpecifierContext ctx) {
    LinkedList<String> args = new LinkedList<>();

    while (true) {
        Token<?> token = stack.pop();
        if (token == SPECIFIER_MARKER) {
            break;
        } else {
            args.addFirst((String) token.getValue());
        }
    }
    String specifier = args.removeFirst();
    List<String> arg = args.size() > 0 ? args : new ArrayList<>();
    Function<Long, Predicate<Long>> predicate = null;
    try {
        if (specifier.equals("THIS DAY OF THE WEEK") || specifier.equals("THIS DAY OF WEEK")) {
            predicate = now -> DayPredicates.dayOfWeekPredicate(DayPredicates.getDayOfWeek(now));
        } else {
            final Predicate<Long> dayOfWeekPredicate = DayPredicates.create(specifier, arg);
            predicate = now -> dayOfWeekPredicate;
        }
        stack.push(new Token<>(predicate, Function.class));
    } catch (Throwable t) {
        throwable = t;
    }
}

From source file:org.dspace.app.webui.cris.controller.admin.FormAdministrationOUController.java

@Override
protected Object formBackingObject(HttpServletRequest request) throws Exception {
    String mode = request.getParameter("mode");
    String paramSort = request.getParameter("sort");
    String paramPage = request.getParameter("page");
    String paramDir = request.getParameter("dir");
    String paramOldPage = request.getParameter("oldpage");

    if (paramOldPage != null
            && (paramOldPage.equals(paramPage) || (Integer.parseInt(paramOldPage) == 1 && paramPage == null))) {
        String message = request.getParameter("message");
        request.setAttribute("message", message);
    }//ww  w  .  jav a2s  .  c  om

    String sort = paramSort != null ? paramSort : "id";
    String dir = paramDir != null ? paramDir : "asc";
    int page = paramPage != null ? Integer.parseInt(paramPage) : 1;
    long count = applicationService.count(OrganizationUnit.class);
    Integer pagesize = Integer.parseInt(ConfigurationManager.getProperty(CrisConstants.CFG_MODULE,
            "project.administration.table.pagesize"));

    //mode position only when administrator click on direct link on RP page  
    Integer id = null;
    if (mode != null && mode.equals("position") && paramPage == null && paramSort == null) {
        String id_s = request.getParameter("id");
        id = Integer.parseInt(id_s);
        page = id / pagesize + 1;
    }

    List<OrganizationUnit> researchers = applicationService.getPaginateList(OrganizationUnit.class, sort,
            "desc".equals(dir), page, pagesize);
    LinkedList<OrganizationUnitDTO> objectList = new LinkedList<OrganizationUnitDTO>();
    for (OrganizationUnit r : researchers) {
        OrganizationUnitDTO rpd = new OrganizationUnitDTO();
        rpd.setId(r.getId());
        rpd.setSourceID(r.getSourceID());
        rpd.setUuid(r.getUuid());
        rpd.setStatus(r.getStatus());
        rpd.setName(r.getName());
        rpd.setOrganizationUnit(r);
        if ((r.getId()).equals(id)) {
            objectList.addFirst(rpd);
        } else {
            objectList.add(rpd);
        }
    }

    OUDisplayTagData displayList = new OUDisplayTagData(count, objectList, sort, dir, page, pagesize);

    return displayList;

}

From source file:com.griddynamics.banshun.DependencySorter.java

private List<Location> pullLocationListTail(Deque<Location> locations) {
    LinkedList<Location> resolvedLocations = new LinkedList<>();
    List<String> annihilatedExports = new LinkedList<>();

    for (Iterator<Location> it = locations.descendingIterator(); it.hasNext();) {
        Location location = it.next();

        if (annihilatedExports.containsAll(location.getExportBeanNames())) {
            it.remove(); //remove location from unresolved
            resolvedLocations.addFirst(location);

            for (BeanReferenceInfo imp : location.importBeans) {
                if (isSomewhereImported(locations, imp)) {
                    annihilatedExports.add(imp.getServiceName());
                }//from  ww  w.  j  a  v a 2s . co m
            }
            it = locations.descendingIterator(); //reset iterator
        }
    }
    return resolvedLocations;
}

From source file:org.apache.metron.profiler.client.window.WindowProcessor.java

private List<Function<Long, Predicate<Long>>> getPredicates() {
    LinkedList<Function<Long, Predicate<Long>>> predicates = new LinkedList<>();
    while (true) {
        Token<?> token = stack.pop();
        if (token == LIST_MARKER) {
            break;
        } else {//from  w w w  . j a va 2 s  .c  o  m
            predicates.addFirst((Function<Long, Predicate<Long>>) token.getValue());
        }
    }
    return predicates;
}

From source file:com.projity.pm.graphic.spreadsheet.common.CommonSpreadSheetModel.java

public LinkedList getPreviousVisibleNodesFromRow(int row) {
    LinkedList siblings = null;
    for (int r = row - 1; r >= 0; r--) {
        Node node = getNodeInRow(r);
        if (node.getImpl() instanceof Assignment)
            continue;
        if (siblings == null)
            siblings = new LinkedList();
        siblings.addFirst(node);
        if (!node.isVoid())
            return siblings;
    }//  www. j a v  a 2  s  . co m
    return null; //no need to move nodes in this case since they are children of root
}