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:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java

private NestedListContainer buildNestedList(SpanManager sm, ContentElementParsingParameters cepp,
        LinkedList<Span> lineSpans, lineType listType) {

    boolean numbered = listType == lineType.NESTEDLIST_NR;
    NestedListContainer result = new NestedListContainer(numbered);

    if (calculateSrcSpans) {
        result.setSrcSpan(new SrcSpan(sm.getSrcPos(lineSpans.getFirst().getStart()), -1));
    }/*from  ww w  .  j  a  v a2  s. c om*/

    LinkedList<Span> nestedListSpans = new LinkedList<Span>();
    while (!lineSpans.isEmpty()) {
        Span s = lineSpans.getFirst();
        if (listType != getLineType(sm, s)) {
            break;
        }
        nestedListSpans.add(new Span(s.getStart() + 1, s.getEnd()).trim(sm));
        lineSpans.removeFirst();
    }
    sm.manageList(nestedListSpans);

    if (calculateSrcSpans) {
        result.getSrcSpan().setEnd(sm.getSrcPos(nestedListSpans.getLast().getEnd()));
    }

    while (!nestedListSpans.isEmpty()) {
        Span s = nestedListSpans.getFirst();
        lineType t = getLineType(sm, s);
        if (t == lineType.NESTEDLIST || t == lineType.NESTEDLIST_NR) {
            result.add(buildNestedList(sm, cepp, nestedListSpans, t));
        } else {
            nestedListSpans.removeFirst();
            result.add((NestedListElement) parseContentElement(sm, cepp, s, new NestedListElement()));
        }
    }

    sm.removeManagedList(nestedListSpans);

    return result;
}

From source file:hr.fer.spocc.regex.AbstractRegularExpression.java

protected RegularExpression<T> createParseTree(List<RegularExpressionElement> elements) {

    //      System.out.println(">>> Parsing regexp: "+elements);

    /**/*from  ww w .j av  a 2  s .  co  m*/
     * Stack which contains parts of regular expression 
     * which are not yet used
     * by the operator. In addition, <code>null</code> values
     * can be pushed onto this stack to indicate that 
     * the symbols to the right are grouped by the parenthesis.
     * 
     */
    LinkedList<RegularExpression<T>> symbolStack = new LinkedList<RegularExpression<T>>();

    /**
     * Operator stack
     */
    LinkedList<RegularExpressionOperator> opStack = new LinkedList<RegularExpressionOperator>();

    boolean sentinelParentheses = false;

    //      if (this.elements.get(0).getElementType() 
    //            != RegularExpressionElementType.LEFT_PARENTHESIS
    //         || this.elements.get(elements.size()-1).getElementType()
    //         != RegularExpressionElementType.RIGHT_PARENTHESIS) {
    sentinelParentheses = true;
    symbolStack.push(null);
    opStack.push(null);
    //      }

    int ind = -1;

    Iterator<RegularExpressionElement> iter = elements.iterator();
    while (iter.hasNext() || sentinelParentheses) {
        ++ind;
        RegularExpressionElement e;
        if (iter.hasNext()) {
            e = iter.next();
        } else { // osiguraj dodatnu iteraciju za umjetnu zadnju )
            e = RegularExpressionElements.RIGHT_PARENTHESIS;
            sentinelParentheses = false;
        }

        switch (e.getElementType()) {
        case SYMBOL:
            symbolStack.push(createTrivial(elements.subList(ind, ind + 1)));
            break;
        default:
            RegularExpressionOperator curOp = (e.getElementType() == RegularExpressionElementType.OPERATOR
                    ? (RegularExpressionOperator) e
                    : null);

            int priority = (curOp != null ? curOp.getPriority() : -1);

            if (e.getElementType() != RegularExpressionElementType.LEFT_PARENTHESIS) {

                //               System.out.println("Pre-while symbolStack: "+symbolStack);

                while (!opStack.isEmpty() && opStack.getFirst() != null
                        && opStack.getFirst().getPriority() >= priority && symbolStack.getFirst() != null) {

                    RegularExpressionOperator op = opStack.pop();
                    int arity = op.getArity();
                    int elementCount = 0;

                    //                  System.out.println("POP: "+op);

                    @SuppressWarnings("unchecked")
                    RegularExpression<T>[] operands = new RegularExpression[arity];
                    for (int i = arity - 1; i >= 0; --i) {
                        if (symbolStack.isEmpty()) {
                            throw new IllegalArgumentException("Missing ( after");
                        } else if (symbolStack.getFirst() == null) {
                            throw new IllegalArgumentException("Missing operand #" + (arity - i)
                                    + " for the operator " + op + " before index " + ind);
                        }
                        operands[i] = symbolStack.pop();
                        elementCount += operands[i].size();
                    }

                    RegularExpression<T> regex = createComposite(elements.subList(ind - elementCount - 1, ind),
                            op, operands);

                    //                  System.err.println(regex);
                    //                  System.err.println(regex.getSubexpression(0));

                    symbolStack.push(regex);

                    //                  System.out.println("Group: "+
                    //                        ArrayToStringUtils.toString(operands, "\n"));
                    //                  System.out.println("End group");
                    //                  System.out.println("Evaluated [" + (ind-elementCount-1)
                    //                        + ", " + ind + "): "+regex);
                    //                  System.out.println("Symbol stack: "+symbolStack);
                    //                  System.out.println("Op stack: "+opStack);
                    //                  System.out.println("---");

                }
            }

            if (curOp != null) {
                opStack.push(curOp);
            } else {
                switch (e.getElementType()) {
                case LEFT_PARENTHESIS:
                    symbolStack.push(null);
                    opStack.push(null);
                    break;
                default: // ako je )
                    Validate.isTrue(symbolStack.size() >= 2,
                            "Exactly one expression is expected " + "inside parentheses before index " + ind);

                    // pop left bracket (null) from the operator stack
                    Object nullValue = opStack.pop();
                    Validate.isTrue(nullValue == null);

                    // pop left bracket (null) from the symbol stack
                    RegularExpression<T> regex = symbolStack.pop();
                    nullValue = symbolStack.pop();

                    // check if left bracket was removed indeed
                    //                  Validate.isTrue(nullValue == null, 
                    //                        "Expected ( at index " + (ind-regex.size()-1));

                    // expand the expression if parentheses are not sentinel
                    if (sentinelParentheses) { // XXX neki drugi flag bolje
                        //                     System.out.print("Expand [" 
                        //                           + (ind - regex.size() - 1) + ", "
                        //                           + (ind + 1) + "]: ");
                        //                     System.out.println("[regex size = "+regex.size()
                        //                           + "]");
                        regex = createExpanded(regex, elements.subList(ind - regex.size() - 1, ind + 1));

                        //                     System.out.println(" -> "+regex);
                    }

                    // and put back the expression inside parentheses
                    symbolStack.push(regex);
                }
            }

        } // end of switch

        //         System.out.println("----- " + ind + " ----");
        //         System.out.println("Symbol stack: "+symbolStack);
        //         System.out.println("Op stack: "+opStack);
    }

    //Validate.isTrue(symbolStack.size() == 1);
    //Validate.isTrue(opStack.isEmpty());

    return symbolStack.pop();
}

From source file:gallery.service.sitemap.SitemapServiceImpl.java

@Override
@Transactional(readOnly = true)/* w w w.  ja  v  a  2 s . c  o m*/
public void createSitemap() {
    if (generating) {
        logger.info("xml is allready generating ...");
        return;
    }
    try {
        logger.info("start generate xml");
        generating = true;
        long time = System.currentTimeMillis();
        File base = new File(path_tmp);
        try {
            if (base.exists()) {
                Index index = new Index(10000, base, gallery.web.Config.SITE_NAME);
                Sitemap sitemap = index.getChild();

                List<Pages> pages = pages_service.getByPropertiesValueOrdered(SITEMAP_NAMES, SITEMAP_WHERE,
                        new Object[] { null, Boolean.TRUE }, null, null);
                LinkedList<Long> pages_unhandled = new LinkedList<Long>();
                int k = 0;
                while (k < pages.size()) {
                    Pages p = pages.get(k);
                    if (!p.getLast()) {
                        pages_unhandled.add(p.getId());
                        sitemap.addRecord("index.htm?id_pages_nav=" + p.getId(), "daily", "0.8");
                    } else {
                        //check type
                        if (p.getType().equals(gallery.web.controller.pages.types.WallpaperGalleryType.TYPE)) {
                            Long id_pages = p.getId();
                            List ids = wallpaper_service.getSingleProperty("id", SITEMAP_WHERE,
                                    new Object[] { id_pages, Boolean.TRUE }, 0, 0, null, null);
                            int j = 0;
                            for (int i = 0; i < ids.size(); i = i
                                    + gallery.web.controller.pages.types.WallpaperGalleryType.CATEGORY_WALLPAPERS) {
                                sitemap.addRecord(
                                        "index.htm?id_pages_nav=" + id_pages + "&amp;page_number=" + j, "daily",
                                        "0.9");
                                j++;
                            }
                            for (Object id_wallpaper : ids) {
                                sitemap.addRecord("index.htm?id_pages_nav=" + id_pages + "&amp;id_photo_nav="
                                        + id_wallpaper, "daily", "0.7");
                            }
                        } else {
                            sitemap.addRecord("index.htm?id_pages_nav=" + p.getId(), "daily", "0.9");
                        }
                    }
                    k++;
                    if ((k >= pages.size()) && (!pages_unhandled.isEmpty())) {
                        pages = pages_service.getByPropertiesValueOrdered(SITEMAP_NAMES, SITEMAP_WHERE,
                                new Object[] { pages_unhandled.removeFirst(), Boolean.TRUE }, null, null);
                        k = 0;
                    }
                }
                sitemap.close();
                //moving to web content
                clearSitemap();
                File f = new File(path_tmp);
                File[] files = f.listFiles();
                for (File file : files) {
                    String name = file.getName();
                    if ((name.startsWith(core.sitemap.model.Config.SITEMAP_PREFIX)
                            || name.startsWith(core.sitemap.model.Config.INDEX_PREFIX))
                            && name.endsWith(core.sitemap.model.Config.XML_SUFFIX)) {
                        File new_file = new File(path, file.getName());
                        file.renameTo(new_file);
                    }
                }
            }
        } catch (IOException ex) {
            logger.error("error while generating sitemap", ex);
        }
        time = System.currentTimeMillis() - time;
        logger.info("end generate xml. generated in: " + time);
    } finally {
        generating = false;
    }
}

From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java

private SectionContainer parseSections(SpanManager sm, ContentElementParsingParameters cepp,
        LinkedList<Span> lineSpans) {

    List<SectionContent> contentSections = new ArrayList<SectionContent>();

    SectionContent sc = new SectionContent(1);

    if (calculateSrcSpans) {
        sc.setSrcSpan(new SrcSpan(sm.getSrcPos(lineSpans.getFirst().getStart()), -1));
    }//w  ww  .  java2s .c  o  m

    // Identify the Line Type and call the necessary Function for the
    // further handling...
    while (!lineSpans.isEmpty()) {

        Span s = lineSpans.getFirst();

        lineType t = getLineType(sm, s);
        switch (t) {
        case SECTION:
            contentSections.add(sc);
            int level = getSectionLevel(sm, s);
            sc = new SectionContent(
                    parseContentElement(sm, cepp, new Span(s.getStart() + level, s.getEnd() - level).trim(sm)),
                    level);
            lineSpans.removeFirst();

            if (calculateSrcSpans) {
                sc.setSrcSpan(new SrcSpan(sm.getSrcPos(s.getStart()), -1));
            }

            break;

        case HR:
            // remove the HR (----) and handle the rest as a parapraph line
            removeHr(sm, s);
            t = lineType.PARAGRAPH;
        case PARAGRAPH:
        case PARAGRAPH_BOXED:
        case PARAGRAPH_INDENTED:
            sc.addParagraph(buildParagraph(sm, cepp, lineSpans, t));
            break;

        case NESTEDLIST:
        case NESTEDLIST_NR:
            sc.addNestedList(buildNestedList(sm, cepp, lineSpans, t));
            break;

        case DEFINITIONLIST:
            sc.addDefinitionList(buildDefinitionList(sm, cepp, lineSpans));
            break;

        case TABLE:
            sc.addTable(buildTable(sm, cepp, lineSpans));
            break;

        case EMPTYLINE:
            lineSpans.removeFirst();
            break;

        default:
            logger.error("unknown lineStart!: \"" + sm.substring(s) + "\"");
            lineSpans.removeFirst();
        }
    }

    // add the remaining Section to the list.
    contentSections.add(sc);

    return buildSectionStructure(contentSections);
}

From source file:org.opendatakit.sync.aggregate.AggregateSynchronizer.java

/**
 * Get all the files under the given folder, excluding those directories
 * that are the concatenation of folder and a member of excluding. If the
 * member of excluding is a directory, none of its children will be synched
 * either.//from  ww  w . j a  v  a  2s . com
 * <p>
 * If the folder doesn't exist it returns an empty list.
 * <p>
 * If the file exists but is not a directory, logs an error and returns an
 * empty list.
 * 
 * @param folder
 * @param excluding
 *            can be null--nothing will be excluded. Should be relative to
 *            the given folder.
 * @param relativeTo
 *            the path to which the returned paths will be relative. A null
 *            value makes them relative to the folder parameter. If it is
 *            non null, folder must start with relativeTo, or else the files
 *            in folder could not possibly be relative to relativeTo. In
 *            this case will throw an IllegalArgumentException.
 * @return the relative paths of the files under the folder--i.e. the paths
 *         after the folder parameter, not including the first separator
 * @throws IllegalArgumentException
 *             if relativeTo is not a substring of folder.
 */
private List<String> getAllFilesUnderFolder(File baseFolder, final Set<String> excludingNamedItemsUnderFolder) {

    String appName = ODKFileUtils.extractAppNameFromPath(baseFolder);

    // Return an empty list of the folder doesn't exist or is not a
    // directory
    if (!baseFolder.exists()) {
        return new ArrayList<String>();
    } else if (!baseFolder.isDirectory()) {
        log.e(LOGTAG, "[getAllFilesUnderFolder] folder is not a directory: " + baseFolder.getAbsolutePath());
        return new ArrayList<String>();
    }

    // construct the set of starting directories and files to process
    File[] partials = baseFolder.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            if (excludingNamedItemsUnderFolder == null) {
                return true;
            } else {
                return !excludingNamedItemsUnderFolder.contains(pathname.getName());
            }
        }
    });

    if (partials == null) {
        return Collections.emptyList();
    }

    LinkedList<File> unexploredDirs = new LinkedList<File>();
    List<File> nondirFiles = new ArrayList<File>();

    // copy the starting set into a queue of unexploredDirs
    // and a list of files to be sync'd
    for (int i = 0; i < partials.length; ++i) {
        if (partials[i].isDirectory()) {
            unexploredDirs.add(partials[i]);
        } else {
            nondirFiles.add(partials[i]);
        }
    }

    while (!unexploredDirs.isEmpty()) {
        File exploring = unexploredDirs.removeFirst();
        File[] files = exploring.listFiles();
        for (File f : files) {
            if (f.isDirectory()) {
                // we'll need to explore it
                unexploredDirs.add(f);
            } else {
                // we'll add it to our list of files.
                nondirFiles.add(f);
            }
        }
    }

    List<String> relativePaths = new ArrayList<String>();
    // we want the relative path, so drop the necessary bets.
    for (File f : nondirFiles) {
        // +1 to exclude the separator.
        relativePaths.add(ODKFileUtils.asRelativePath(appName, f));
    }
    return relativePaths;
}

From source file:com.ichi2.libanki.Finder.java

private String _findField(String field, String val) {
    /*/*from   ww w. ja v  a  2 s .  c om*/
     * We need two expressions to query the cards: One that will use JAVA REGEX syntax and another
     * that should use SQLITE LIKE clause syntax.
     */
    String sqlVal = val.replace("%", "\\%") // For SQLITE, we escape all % signs
            .replace("*", "%"); // And then convert the * into non-escaped % signs

    /*
     * The following three lines make sure that only _ and * are valid wildcards.
     * Any other characters are enclosed inside the \Q \E markers, which force
     * all meta-characters in between them to lose their special meaning
     */
    String javaVal = val.replace("_", "\\E.\\Q").replace("*", "\\E.*\\Q");
    /*
     * For the pattern, we use the javaVal expression that uses JAVA REGEX syntax
     */
    Pattern pattern = Pattern.compile("\\Q" + javaVal + "\\E", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

    // find models that have that field
    Map<Long, Object[]> mods = new HashMap<Long, Object[]>();
    try {
        for (JSONObject m : mCol.getModels().all()) {
            JSONArray flds = m.getJSONArray("flds");
            for (int fi = 0; fi < flds.length(); ++fi) {
                JSONObject f = flds.getJSONObject(fi);
                if (f.getString("name").equalsIgnoreCase(field)) {
                    mods.put(m.getLong("id"), new Object[] { m, f.getInt("ord") });
                }
            }
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    if (mods.isEmpty()) {
        // nothing has that field
        return null;
    }
    LinkedList<Long> nids = new LinkedList<Long>();
    Cursor cur = null;
    try {
        /*
         * Here we use the sqlVal expression, that is required for LIKE syntax in sqllite.
         * There is no problem with special characters, because only % and _ are special
         * characters in this syntax.
         */
        cur = mCol.getDb().getDatabase()
                .rawQuery("select id, mid, flds from notes where mid in "
                        + Utils.ids2str(new LinkedList<Long>(mods.keySet())) + " and flds like ? escape '\\'",
                        new String[] { "%" + sqlVal + "%" });

        while (cur.moveToNext()) {
            String[] flds = Utils.splitFields(cur.getString(2));
            int ord = (Integer) mods.get(cur.getLong(1))[1];
            String strg = flds[ord];
            if (pattern.matcher(strg).matches()) {
                nids.add(cur.getLong(0));
            }
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    if (nids.isEmpty()) {
        return "0";
    }
    return "n.id in " + Utils.ids2str(nids);
}

From source file:de.qspool.clementineremote.ui.fragments.LibraryFragment.java

@SuppressLint({ "InlinedApi", "NewApi" })
@Override/*  w  w w .j  av a  2s .co m*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_library, container, false);

    mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.library_refresh_layout);
    mEmptyLibrary = (SwipeRefreshLayout) view.findViewById(R.id.library_refresh_empty_layout);
    mSwipeRefreshLayout.setOnRefreshListener(this);
    mEmptyLibrary.setOnRefreshListener(this);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.orange);
    mEmptyLibrary.setColorSchemeResources(R.color.orange);

    mList = (ListView) view.findViewById(R.id.library);

    mLibraryEmptyText = (TextView) mEmptyLibrary.findViewById(R.id.library_empty_txt);

    mList.setOnItemClickListener(oiclLibraryClick);
    mList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    mList.setMultiChoiceModeListener(new MultiChoiceModeListener() {
        @Override
        public boolean onActionItemClicked(ActionMode mode, android.view.MenuItem item) {
            SparseBooleanArray checkedPositions = mList.getCheckedItemPositions();
            final LinkedList<SongSelectItem> selectedItems = new LinkedList<>();
            final LinkedList<String> urls = new LinkedList<>();
            mLibraryQueriesDone = 0;

            for (int i = 0; i < checkedPositions.size(); ++i) {
                int position = checkedPositions.keyAt(i);
                if (checkedPositions.valueAt(i)) {
                    selectedItems.add(mAdapters.getLast().getItem(position));
                }
            }

            for (SongSelectItem libraryItem : selectedItems) {
                OnSongSelectFinishedListener listener;

                switch (item.getItemId()) {
                case R.id.library_context_add:

                    listener = new OnSongSelectFinishedListener() {
                        @Override
                        public void OnSongSelectFinished(LinkedList<SongSelectItem> l) {
                            addSongsToPlaylist(l);
                        }
                    };

                    break;
                case R.id.library_context_download:
                    listener = new OnSongSelectFinishedListener() {
                        @Override
                        public void OnSongSelectFinished(LinkedList<SongSelectItem> l) {
                            for (SongSelectItem libItem : l) {
                                urls.add(libItem.getUrl());
                            }
                            mLibraryQueriesDone++;

                            // Have we got all queries?
                            if (mLibraryQueriesDone == selectedItems.size() && !urls.isEmpty()) {
                                DownloadManager.getInstance()
                                        .addJob(ClementineMessageFactory.buildDownloadSongsMessage(
                                                ClementineRemoteProtocolBuffer.DownloadItem.Urls, urls));
                            }

                        }
                    };

                    break;
                default:
                    return false;
                }
                queryLibraryItems(libraryItem, listener);
            }
            mode.finish();
            return true;
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, android.view.Menu menu) {
            android.view.MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.library_context_menu, menu);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getActivity().getWindow()
                        .setStatusBarColor(ContextCompat.getColor(getActivity(), R.color.grey_cab_status));
            }

            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, android.view.Menu menu) {
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                getActivity().getWindow()
                        .setStatusBarColor(ContextCompat.getColor(getActivity(), R.color.actionbar_dark));
            }
        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
        }
    });

    createRootAdapter();

    showList();

    mActionBar.setTitle("");
    mActionBar.setSubtitle("/");

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    prefs.registerOnSharedPreferenceChangeListener(this);

    setHasOptionsMenu(true);

    return view;
}

From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java

private Table buildTable(SpanManager sm, ContentElementParsingParameters cepp, LinkedList<Span> lineSpans) {

    Table result = new Table();
    int col = -1;
    int row = 0;/*  w  w  w.  j a  va2 s.  co m*/
    int subTables = 0;
    LinkedList<Span> tableDataSpans = new LinkedList<Span>();
    sm.manageList(tableDataSpans);

    if (calculateSrcSpans) {
        result.setSrcSpan(new SrcSpan(sm.getSrcPos(lineSpans.getFirst().getStart()), -1));
    }

    lineSpans.removeFirst();

    while (!lineSpans.isEmpty()) {
        Span s = lineSpans.removeFirst();

        int pos = s.nonWSCharPos(sm);
        char c0 = s.charAt(pos, sm);
        char c1 = s.charAt(pos + 1, sm);

        if (subTables == 0 && (c0 == '!' || c0 == '|')) {
            if (!tableDataSpans.isEmpty()) {
                lineSpans.addFirst(s);

                SrcSpan ei = null;
                if (calculateSrcSpans) {
                    ei = new SrcSpan(sm.getSrcPos(tableDataSpans.getFirst().getStart() - 1) + 1, -1);
                }

                TableElement te = new TableElement(parseSections(sm, cepp, tableDataSpans), row, col);
                te.setSrcSpan(ei);
                result.addTableElement(te);
                lineSpans.removeFirst();
            }

            col++;
            if (c1 == '-') {
                row++;
                col = -1;
                continue;
            } else if (c0 == '|' && c1 == '}') {
                sm.removeManagedList(tableDataSpans);

                if (calculateSrcSpans) {
                    result.getSrcSpan().setEnd(sm.getSrcPos(s.getEnd()));
                }

                return result;
            } else if (c0 == '|' && c1 == '+') {
                result.setTitleElement(
                        parseContentElement(sm, cepp, new Span(s.getStart() + pos + 2, s.getEnd()).trim(sm)));
                continue;
            } else {
                int multipleCols;
                if ((multipleCols = sm.indexOf("||", s.getStart() + pos + 1, s.getEnd())) != -1) {
                    lineSpans.addFirst(new Span(multipleCols + 1, s.getEnd()));
                    s.setEnd(multipleCols);
                }

                int optionTagPos = sm.indexOf("|", s.getStart() + pos + 1, s.getEnd());

                if (optionTagPos != -1) {
                    s.setStart(optionTagPos + 1).trim(sm);
                } else {
                    s.adjustStart(pos + 1).trim(sm);
                }
            }
        } else if (c0 == '|' && c1 == '}') {
            subTables--;
        } else if (c0 == '{' && c1 == '|') {
            subTables++;
        }

        tableDataSpans.addLast(s);
    }

    if (tableDataSpans.size() != 0) {

        SrcSpan ei = null;
        if (calculateSrcSpans) {
            ei = new SrcSpan(sm.getSrcPos(tableDataSpans.getFirst().getStart() - 1) + 1, -1);
        }

        TableElement te = new TableElement(parseSections(sm, cepp, tableDataSpans), row, col);
        te.setSrcSpan(ei);

        result.addTableElement(te);
    }

    sm.removeManagedList(tableDataSpans);

    if (calculateSrcSpans) {
        result.getSrcSpan().setEnd(-1);
    }

    return result;
}

From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java

private DefinitionList buildDefinitionList(SpanManager sm, ContentElementParsingParameters cepp,
        LinkedList<Span> lineSpans) {
    List<ContentElement> content = new ArrayList<ContentElement>();

    Span s = lineSpans.removeFirst();/*from  www. ja  v a2 s  .c o  m*/

    int temp = sm.indexOf(":", s);
    if (temp == -1) {
        content.add(parseContentElement(sm, cepp, new Span(s.getStart() + 1, s.getEnd())));
    } else {
        content.add(parseContentElement(sm, cepp, new Span(temp + 1, s.getEnd())));
        content.add(0, parseContentElement(sm, cepp, new Span(s.getStart() + 1, temp)));
    }

    while (!lineSpans.isEmpty()) {
        Span ns = lineSpans.getFirst();
        if (sm.charAt(ns.getStart()) != ':') {
            break;
        }
        lineSpans.removeFirst();
        content.add(parseContentElement(sm, cepp, new Span(ns.getStart() + 1, ns.getEnd())));
    }

    DefinitionList result = new DefinitionList(content);

    if (calculateSrcSpans) {
        result.setSrcSpan(
                new SrcSpan(sm.getSrcPos(s.getStart()), content.get(content.size() - 1).getSrcSpan().getEnd()));
    }

    return result;
}

From source file:com.cablelabs.sim.PCSim2.java

/**
 * This method performs the actual task of starting the test
 * and waiting for it to complete./*from   w w  w. j  a  va2  s . co  m*/
 *
 */
private void executeTest() {
    // First of all make sure that the we reset the 
    // complete flag before starting the test
    complete = false;
    testPassed = null;

    File dut = new File(activeDUTFile);
    String[] settingChanges = ss.setDUTProperties(dut.getAbsolutePath());
    if (settingChanges == null) {
        logger.fatal(PC2LogCategory.Parser, subCat,
                "DUTConfiguration property information could not be found and loaded.");
        setTestPassed(false);
        setTestComplete();
    } else {

        stacks.updateRegistrarDisplay(settingChanges);

        boolean parsed = parseAndStart();
        // Before starting test log if the Global Registrar is running or not.
        if (globalRegEnabled) {
            logger.info(PC2LogCategory.PCSim2, subCat, "The global registrar is enabled.");

        } else
            logger.info(PC2LogCategory.PCSim2, subCat, "The global registrar is disabled.");

        if (activeModels.size() > 0 && parsed) {
            ui.startingTest(ss.getCurrentRunNumber(), activeTestScriptFile, activeDUTFile);
            logger.info(PC2LogCategory.LOG_MSG, "",
                    "Commencing test \"" + activeTestScriptFile + "\" for DUT \"" + activeDUTFile + "\".");

            while (!complete) {

                try {
                    Thread.sleep(250);
                } catch (InterruptedException ie) {

                } catch (Exception e) {
                    String err = "Simulator failed to sleep. Terminating test.";
                    logger.fatal(PC2LogCategory.Parser, subCat, err, e);
                    setTestPassed(false);
                    setTestComplete();
                }
            }

            // Determine if we are using the new validation or not
            boolean useValidate = doc.useValidate();
            if (useValidate) {
                if (testPassed == null)
                    testPassed = doc.validateTest();
                else
                    testPassed &= doc.validateTest();
            } else if (testPassed == null)
                testPassed = true;

            // Document the test results
            // Use the logMsg category to insure that the information
            // is displayed
            if (testPassed) {
                logger.info(PC2LogCategory.LOG_MSG, subCat, "Test \"" + doc.getName() + "\" Passed.\n"
                        + ((useValidate) ? doc.getTestStats() : "") + logger.dumpLogStats());
            } else
                logger.info(PC2LogCategory.LOG_MSG, subCat, "Test \"" + doc.getName() + "\" Failed.\n"
                        + ((useValidate) ? doc.getTestStats() : "") + logger.dumpLogStats());
            displayResults();
            generateResults(doc);
        } else {
            setTestPassed(false);
            String err = "PCSim2 failed to parse the script or there were no models to conduct the test."
                    + "Terminating test. Declaring test case failure.";
            logger.fatal(PC2LogCategory.Model, subCat, err);

            setTestComplete();
            displayResults();
            if (doc != null)
                generateResults(doc);

        }
    }
    // Now clean up for the next test
    ss.reset();
    Stacks.reset();
    doc = null;
    autoProvisioned = false;
    logger.debug(PC2LogCategory.PCSim2, subCat,
            "Resetting the auto provisioned reboot flag to " + autoProvisioned + ".");
    // We need to clear the message queue of any
    // models that only exist for the length of the
    // test. Information in a global model should 
    // remain for operations that could occur between
    // tests, eg. registrar
    ListIterator<PC2Models> iter = activeModels.listIterator();
    LinkedList<Integer> fsmUIDs = new LinkedList<Integer>();
    while (iter.hasNext()) {
        PC2Models model = iter.next();
        fsmUIDs.add(model.getFsmUID());
    }
    if (!fsmUIDs.isEmpty())
        q.reset(fsmUIDs);

    if (activeModels != null) {

        activeModels.clear();
    }
    logger.clear();

}