Example usage for java.util ListIterator previousIndex

List of usage examples for java.util ListIterator previousIndex

Introduction

In this page you can find the example usage for java.util ListIterator previousIndex.

Prototype

int previousIndex();

Source Link

Document

Returns the index of the element that would be returned by a subsequent call to #previous .

Usage

From source file:com.tacitknowledge.util.migration.jdbc.SqlScriptMigrationTask.java

/**
 * Executes the passed sql in the passed context.
 *
 * @param ctx       the <code>MigrationContext> to execute the SQL in
 * @param sqlToExec the SQL to execute/*from   w  w w  . j  a  va2 s. c om*/
 * @throws MigrationException thrown if there is an error when executing the SQL
 */
private void executeSql(MigrationContext ctx, String sqlToExec) throws MigrationException {
    JdbcMigrationContext context = (JdbcMigrationContext) ctx;

    Connection conn = null;
    Statement stmt = null;
    String sqlStatement = "";
    ListIterator listIterator = null;
    try {
        conn = context.getConnection();

        // cleaning the slate before we execute the patch.
        // This was inspired by a Sybase ASE server that did not allow
        // ALTER TABLE statements in multi-statement transactions.  Instead of putting
        // a if(sybase) conditional, we decided to clean the slate for everyone.
        context.commit();

        List sqlStatements = getSqlStatements(context, sqlToExec);
        for (listIterator = sqlStatements.listIterator(); listIterator.hasNext();) {
            sqlStatement = (String) listIterator.next();
            log.debug(getName() + ": Attempting to execute: " + sqlStatement);

            stmt = conn.createStatement();

            // handle sybase special case with illegal commands in multi
            // command transactions
            if (isSybase(context) && SybaseUtil.containsIllegalMultiStatementTransactionCommand(sqlStatement)) {
                log.warn("Committing current transaction since patch " + getName()
                        + " contains commands that are not allowed in multi statement"
                        + " transactions.  If the patch contains errors, this patch may"
                        + " not be rolled back cleanly.");
                context.commit();
                stmt.execute(sqlStatement);
                context.commit();
            } else // regular case
            {
                stmt.execute(sqlStatement);
            }

            SqlUtil.close(null, stmt, null);
        }

        context.commit();
    } catch (Exception e) {
        String message = getName() + ": Error running SQL at statement number " + listIterator.previousIndex()
                + " \"" + sqlStatement + "\"";
        log.error(message, e);

        if (e instanceof SQLException) {
            if (((SQLException) e).getNextException() != null) {
                log.error("Chained SQL Exception", ((SQLException) e).getNextException());
            }
        }

        context.rollback();
        throw new MigrationException(message, e);
    } finally {
        SqlUtil.close(null, stmt, null);
    }
}

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

/**
 * Main thread simply looks for notification that the
 * test is complete, informs the various protocol stacks
 * to shutdown and then terminates the test.
 *
 *///from   w ww.  j av  a2s.c om
public void run() {
    mainThread = Thread.currentThread();
    // GAREY test code       int count = 0;
    while (!shutdown) {
        // First determine if there are any tests to conduct
        boolean configsToProcess = false;
        synchronized (dutConfigsToRead) {
            synchronized (dutConfigsToRemove) {
                if (dutConfigsToRead.size() > 0 || dutConfigsToRemove.size() > 0) {
                    configsToProcess = true;
                }
            }
        }

        if (!configsToProcess && closeBatchFile) {
            if (ss != null) {
                ss.closeBatch();

            }
            if (stacks != null) {
                stacks.shutdown();
            }
            closeBatchFile = false;
            platformSettingsFile = null;
            if (globalRegEnabled) {
                globalRegFile = null;
                GlobalRegistrar.setMasterFSM(null, Transport.UDP);
                globalRegEnabled = false;
            }
            if (presenceServerEnabled) {
                presenceServerFile = null;
                presenceServerEnabled = false;
            }
        }
        // Next see if we are ready to run some test pairs
        // This can only be done if there are no dutConfigs to
        // process in add or remove lists
        else if (dutConfigFiles.size() > 0 && testScriptFiles.size() > 0 && !configsToProcess
                && platformSettingsFile != null) {
            try {
                if (dutPrimary) {

                    ListIterator<String> duts = dutConfigFiles.listIterator();
                    while (duts.hasNext() && !shutdown) {
                        activeDUTFile = duts.next();
                        ListIterator<String> testScripts = testScriptFiles.listIterator();
                        while (testScripts.hasNext() && !shutdown) {
                            activeTestScriptFile = testScripts.next();
                            executeTest();
                        }
                    }
                } else {
                    ListIterator<String> testScripts = testScriptFiles.listIterator();
                    while (testScripts.hasNext() && !shutdown) {
                        activeTestScriptFile = testScripts.next();
                        ListIterator<String> duts = dutConfigFiles.listIterator();
                        while (duts.hasNext() && !shutdown) {
                            activeDUTFile = duts.next();
                            executeTest();
                        }
                    }
                }
                testsComplete();
            }
            // This most likely will happen if the user stop's the tests. When the 
            // user terminates the test, the lists are emptied so that no record is made for 
            // unattempted test pairs.
            catch (ConcurrentModificationException cme) {
                logger.debug(PC2LogCategory.PCSim2, subCat,
                        "Either DUT or Test Script list have changed during test pair execution.");
            }
        } else if (pendingPSFile != null) {
            boolean restart = false;
            // Determine if we need to restart the existing stacks and 
            // configuration parameters of the platform.
            if (platformSettingsFile == null)
                restart = true;
            else if (platformSettingsFile != null) {
                // First we need to remove any UEs that are not being simulated from the
                // table of allowable registering devices.
                Enumeration<String> keys = SystemSettings.getPlatformLabels();
                if (keys != null) {
                    while (keys.hasMoreElements()) {
                        String key = keys.nextElement();
                        if (key.startsWith("UE")) {
                            Properties p = SystemSettings.getSettings(key);
                            LinkedList<String> puis = createRegistrarLabels(p);
                            Stacks.removeSIPRegistrarClient(key, puis);
                        }
                    }
                }
                if (!pendingPSFile.equals(platformSettingsFile))
                    restart = true;
                else if (psLastModified < (new File(platformSettingsFile)).lastModified())
                    restart = true;
            }
            if (restart && stacks != null)
                stacks.restart();
            platformSettingsFile = pendingPSFile;
            pendingPSFile = null;
            File ps = new File(platformSettingsFile);
            psLastModified = ps.lastModified();
            if (!ss.loadPlatformSettings(platformSettingsFile)) {
                logger.fatal(PC2LogCategory.Parser, subCat,
                        "PCSim2 encountered error while trying to read the Platform Settings information.");
                // Clear the file information
                platformSettingsFile = null;
            } else {
                Enumeration<String> labels = SystemSettings.getPlatformLabels();
                if (labels != null) {
                    while (labels.hasMoreElements()) {
                        String ne = labels.nextElement();
                        if (!ne.startsWith(SettingConstants.UE) && !ne.startsWith(SettingConstants.PCSCF)
                                && !ne.startsWith(SettingConstants.SCSCF))
                            continue;
                        Properties p = SystemSettings.getSettings(ne);
                        logNE(ne, p);
                    }
                }

                if (restart) {
                    logger.info(PC2LogCategory.PCSim2, subCat, "Starting servers.");
                    startServers();
                }

            }

            // Next reload the provisioning test script/policy/provisioning file table
            if (platformSettingsFile != null) {
                Properties platform = SystemSettings.getSettings(SettingConstants.PLATFORM);
                String cw = platform.getProperty(SettingConstants.CW_NUMBER);
                if (provDB == null)
                    provDB = new ProvDatabase(cw);
                else
                    provDB.load(cw);
            }

            // Now add all of the real devices in the platform settings to the 
            // allowable registering devices table.
            addRegistrarClients();
        }

        else {
            try {
                if (configsToProcess) {
                    synchronized (dutConfigsToRead) {

                        synchronized (dutConfigsToRemove) {
                            if (dutConfigsToRead.size() > 0 || dutConfigsToRemove.size() > 0) {
                                ListIterator<File> rmIter = dutConfigsToRemove.listIterator();
                                // Loop through the reads 
                                File read = null;
                                if (dutConfigsToRead.size() > 0)
                                    read = dutConfigsToRead.removeFirst();
                                while (read != null) {
                                    int prevRmIndex = -1;
                                    // Make sure the read doesn't also appear in the 
                                    // remove list
                                    while (rmIter.hasNext()) {
                                        File rm = rmIter.next();
                                        if (rm.equals(read)) {
                                            prevRmIndex = rmIter.previousIndex();

                                        }
                                    }
                                    // If the file appears in the remove list at the
                                    // same time we try to read, simply don't read
                                    // and remove from the remove list
                                    if (prevRmIndex != -1) {
                                        dutConfigsToRemove.remove(prevRmIndex);
                                        logger.warn(PC2LogCategory.Parser, subCat, "Skipping reading "
                                                + read.getName()
                                                + " because file was also found in DUT Config remove list.");
                                    } else {
                                        try {
                                            // Load the read file
                                            String neLabel = ss.loadDUTSettings(read.getAbsolutePath(), true,
                                                    false);
                                            if (neLabel != null && neLabel.startsWith("UE")) {
                                                // Now obtains the DUT's IP address and the expected IP address for
                                                // it to register with
                                                Properties p = SystemSettings.getSettings(neLabel);
                                                if (p != null) {
                                                    logNE(neLabel, p);

                                                    LinkedList<String> puis = createRegistrarLabels(p);
                                                    if (puis.size() > 0) {
                                                        Stacks.addSIPRegistrarClient(neLabel, puis);
                                                        // With the new design of using Public User Identifier we will need to
                                                        // use the first entry in the puis as the key for the table
                                                        //                                             dutConfigFileToPUIIndex.put(read, puis.get(0));
                                                        if (SystemSettings.getBooleanSetting(
                                                                SettingConstants.GLOBAL_REGISTRAR)) {
                                                            logger.info(PC2LogCategory.Parser, subCat,
                                                                    "Loaded " + read.getName()
                                                                            + " for global registrar.");
                                                        } else
                                                            logger.info(PC2LogCategory.Parser, subCat, read
                                                                    .getName()
                                                                    + " not loaded for global registrar because registrar is disabled.");
                                                    } else {
                                                        logger.error(PC2LogCategory.Parser, subCat,
                                                                "The DUT configuration file appears to not contain any Public User Identitier.");
                                                    }
                                                } else {
                                                    logger.warn(PC2LogCategory.Parser, subCat, "Failed to load "
                                                            + read.getName() + " for global registrar.");
                                                }
                                            } else if (neLabel != null && neLabel.startsWith("CN")) {
                                                // Since the CN could contain the PCSCF that real UEs
                                                // need to register, temporarily load the file's 
                                                // settings, add the clients and then remove them
                                                ss.setDUTProperties(read.getAbsolutePath());
                                                addRegistrarClients();
                                                ss.reset();
                                            } else {
                                                logger.info(PC2LogCategory.Parser, subCat,
                                                        "No elements added for global register for label "
                                                                + neLabel + " from file " + read.getName()
                                                                + ".");
                                            }
                                        } catch (Exception e) {
                                            logger.error(PC2LogCategory.PCSim2, subCat,
                                                    "The DUT Configuration File defined by ("
                                                            + read.getAbsolutePath()
                                                            + ") could not be processed. File is being dropped.");
                                        }
                                    }
                                    read = null;
                                    if (dutConfigsToRead.size() > 0)
                                        read = dutConfigsToRead.removeFirst();
                                }

                                File rm = null;
                                if (dutConfigsToRemove.size() > 0)
                                    rm = dutConfigsToRemove.removeFirst();
                                while (rm != null) {
                                    try {
                                        String neLabel = ss.loadDUTSettings(rm.getAbsolutePath(), true, true);
                                        if (neLabel != null && neLabel.startsWith("UE")) {
                                            Properties p = SystemSettings.getSettings(neLabel);
                                            LinkedList<String> puis = createRegistrarLabels(p);
                                            Stacks.removeSIPRegistrarClient(neLabel, puis);
                                            logger.info(PC2LogCategory.Parser, subCat,
                                                    "removing client defined by " + rm.getName()
                                                            + " to list of accepted clients for global registrar");
                                        }
                                    } catch (Exception e) {
                                        String err = "Simulator failed to sleep. Terminating test.";
                                        logger.fatal(PC2LogCategory.Parser, subCat, err, e);
                                    }
                                    rm = null;
                                    if (dutConfigsToRemove.size() > 0)
                                        rm = dutConfigsToRemove.removeFirst();
                                }
                                dutConfigsToRead.clear();
                                dutConfigsToRemove.clear();
                            }
                        }
                    }
                } else {
                    // Since there are aren't any dut and test script
                    // files we can simply go to sleep and check again 
                    // later for any work.
                    Thread.sleep(250);
                }

            } catch (InterruptedException ie) {
                String msg = "Simulator sleep interrupted.";
                logger.info(PC2LogCategory.Parser, subCat, msg);
            } catch (Exception e) {
                String err = "Simulator failed to sleep. Terminating test.";
                logger.fatal(PC2LogCategory.Parser, subCat, err, e);
            }
        }
    }
    LogAPI.shutdown();
}

From source file:org.apache.fop.layoutmgr.BlockStackingLayoutManager.java

/** {@inheritDoc} */
@Override//from   ww w. j  a v  a  2  s. c  o  m
public List getChangedKnuthElements(List oldList, int alignment) {
    ListIterator<KnuthElement> oldListIterator = oldList.listIterator();
    KnuthElement currElement = null;
    KnuthElement prevElement = null;
    List<KnuthElement> returnedList = new LinkedList<KnuthElement>();
    List<KnuthElement> returnList = new LinkedList<KnuthElement>();
    int fromIndex = 0;

    // "unwrap" the Positions stored in the elements
    KnuthElement oldElement;
    while (oldListIterator.hasNext()) {
        oldElement = oldListIterator.next();
        assert oldElement.getPosition() != null;
        Position innerPosition = oldElement.getPosition().getPosition();
        if (innerPosition != null) {
            // oldElement was created by a descendant
            oldElement.setPosition(innerPosition);
        } else {
            // oldElement was created by this LM:
            // modify its position in order to recognize it was not created
            // by a child
            oldElement.setPosition(new Position(this));
        }
    }

    // create the iterator
    ListIterator<KnuthElement> workListIterator = oldList.listIterator();
    while (workListIterator.hasNext()) {
        currElement = workListIterator.next();
        if (prevElement != null && prevElement.getLayoutManager() != currElement.getLayoutManager()) {
            // prevElement is the last element generated by the same LM
            BlockLevelLayoutManager prevLM = (BlockLevelLayoutManager) prevElement.getLayoutManager();
            BlockLevelLayoutManager currLM = (BlockLevelLayoutManager) currElement.getLayoutManager();
            boolean somethingAdded = false;
            if (prevLM != this) {
                returnedList.addAll(prevLM.getChangedKnuthElements(
                        oldList.subList(fromIndex, workListIterator.previousIndex()), alignment));
                somethingAdded = true;
            } else {
                // do nothing
            }
            fromIndex = workListIterator.previousIndex();

            /*
             * TODO: why are KnuthPenalties added here,
             *       while in getNextKE they were changed to BreakElements?
             */
            // there is another block after this one
            if (somethingAdded && (this.mustKeepTogether() || prevLM.mustKeepWithNext()
                    || currLM.mustKeepWithPrevious())) {
                // add an infinite penalty to forbid a break between blocks
                returnedList.add(makeZeroWidthPenalty(KnuthPenalty.INFINITE));
            } else if (somethingAdded && !ListUtil.getLast(returnedList).isGlue()) {
                // add a null penalty to allow a break between blocks
                returnedList.add(makeZeroWidthPenalty(KnuthPenalty.INFINITE));
            }
        }
        prevElement = currElement;
    }
    if (currElement != null) {
        LayoutManager currLM = currElement.getLayoutManager();
        if (currLM != this) {
            returnedList.addAll(
                    currLM.getChangedKnuthElements(oldList.subList(fromIndex, oldList.size()), alignment));
        } else {
            // there are no more elements to add
            // remove the last penalty added to returnedList
            if (!returnedList.isEmpty()) {
                ListUtil.removeLast(returnedList);
            }
        }
    }

    // append elements representing space-before
    boolean spaceBeforeIsConditional = true;
    if (fobj instanceof org.apache.fop.fo.flow.Block) {
        spaceBeforeIsConditional = getSpaceBeforeProperty().isDiscard();
    }
    if (adjustedSpaceBefore != 0) {
        if (!spaceBeforeIsConditional) {
            // add elements to prevent the glue to be discarded
            returnList.add(makeZeroWidthBox());
            returnList.add(makeZeroWidthPenalty(KnuthPenalty.INFINITE));
        }

        returnList.add(makeSpaceAdjustmentGlue(adjustedSpaceBefore, Adjustment.SPACE_BEFORE_ADJUSTMENT, false));
    }

    // "wrap" the Position stored in each element of returnedList
    // and add elements to returnList
    for (KnuthElement el : returnedList) {
        el.setPosition(new NonLeafPosition(this, el.getPosition()));
        returnList.add(el);
    }

    // append elements representing space-after
    boolean spaceAfterIsConditional = true;
    if (fobj instanceof org.apache.fop.fo.flow.Block) {
        spaceAfterIsConditional = getSpaceAfterProperty().isDiscard();
    }
    if (adjustedSpaceAfter != 0) {
        if (!spaceAfterIsConditional) {
            returnList.add(makeZeroWidthPenalty(KnuthPenalty.INFINITE));
        }

        returnList.add(makeSpaceAdjustmentGlue(adjustedSpaceAfter, Adjustment.SPACE_AFTER_ADJUSTMENT,
                spaceAfterIsConditional));

        if (!spaceAfterIsConditional) {
            returnList.add(makeZeroWidthBox());
        }
    }

    return returnList;
}

From source file:org.apache.fop.layoutmgr.FlowLayoutManager.java

/** {@inheritDoc} */
@Override//from  ww w. j a va2  s. c o m
public List<KnuthElement> getChangedKnuthElements(List oldList, int alignment) {
    ListIterator<KnuthElement> oldListIterator = oldList.listIterator();
    KnuthElement returnedElement;
    List<KnuthElement> returnedList = new LinkedList<KnuthElement>();
    List<KnuthElement> returnList = new LinkedList<KnuthElement>();
    KnuthElement prevElement = null;
    KnuthElement currElement = null;
    int fromIndex = 0;

    // "unwrap" the Positions stored in the elements
    KnuthElement oldElement;
    while (oldListIterator.hasNext()) {
        oldElement = oldListIterator.next();
        if (oldElement.getPosition() instanceof NonLeafPosition) {
            // oldElement was created by a descendant of this FlowLM
            oldElement.setPosition((oldElement.getPosition()).getPosition());
        } else {
            // thisElement was created by this FlowLM, remove it
            oldListIterator.remove();
        }
    }
    // reset the iterator
    oldListIterator = oldList.listIterator();

    while (oldListIterator.hasNext()) {
        currElement = oldListIterator.next();
        if (prevElement != null && prevElement.getLayoutManager() != currElement.getLayoutManager()) {
            // prevElement is the last element generated by the same LM
            BlockLevelLayoutManager prevLM = (BlockLevelLayoutManager) prevElement.getLayoutManager();
            BlockLevelLayoutManager currLM = (BlockLevelLayoutManager) currElement.getLayoutManager();
            returnedList.addAll(prevLM.getChangedKnuthElements(
                    oldList.subList(fromIndex, oldListIterator.previousIndex()), alignment));
            fromIndex = oldListIterator.previousIndex();

            // there is another block after this one
            if (prevLM.mustKeepWithNext() || currLM.mustKeepWithPrevious()) {
                // add an infinite penalty to forbid a break between blocks
                returnedList.add(new KnuthPenalty(0, KnuthElement.INFINITE, false, new Position(this), false));
            } else if (!ListUtil.getLast(returnedList).isGlue()) {
                // add a null penalty to allow a break between blocks
                returnedList.add(new KnuthPenalty(0, 0, false, new Position(this), false));
            }
        }
        prevElement = currElement;
    }
    if (currElement != null) {
        BlockLevelLayoutManager currLM = (BlockLevelLayoutManager) currElement.getLayoutManager();
        returnedList
                .addAll(currLM.getChangedKnuthElements(oldList.subList(fromIndex, oldList.size()), alignment));
    }

    // "wrap" the Position stored in each element of returnedList
    // and add elements to returnList
    ListIterator<KnuthElement> listIter = returnedList.listIterator();
    while (listIter.hasNext()) {
        returnedElement = listIter.next();
        if (returnedElement.getLayoutManager() != this) {
            returnedElement.setPosition(new NonLeafPosition(this, returnedElement.getPosition()));
        }
        returnList.add(returnedElement);
    }

    return returnList;
}

From source file:org.apache.fop.layoutmgr.inline.LineLayoutManager.java

/**
 * Find hyphenation points for every word in the current paragraph.
 *
 * @param currPar the paragraph whose words will be hyphenated
 *///from   w  w w .j  a va 2 s .  c o  m
private void findHyphenationPoints(Paragraph currPar) {
    // hyphenate every word
    ListIterator currParIterator = currPar.listIterator(currPar.ignoreAtStart);
    // list of TLM involved in hyphenation
    List updateList = new LinkedList();
    KnuthElement firstElement;
    KnuthElement nextElement;
    // current InlineLevelLayoutManager
    InlineLevelLayoutManager currLM = null;
    // number of KnuthBox elements containing word fragments
    int boxCount;
    // number of auxiliary KnuthElements between KnuthBoxes
    int auxCount;
    StringBuffer sbChars;

    // find all hyphenation points
    while (currParIterator.hasNext()) {
        firstElement = (KnuthElement) currParIterator.next();
        //
        if (firstElement.getLayoutManager() != currLM) {
            currLM = (InlineLevelLayoutManager) firstElement.getLayoutManager();
            if (currLM != null) {
                updateList.add(new Update(currLM, currParIterator.previousIndex()));
            } else {
                break;
            }
        } else if (currLM == null) {
            break;
        }

        // collect word fragments, ignoring auxiliary elements;
        // each word fragment was created by a different TextLM
        if (firstElement.isBox() && !firstElement.isAuxiliary()) {
            boxCount = 1;
            auxCount = 0;
            sbChars = new StringBuffer();
            sbChars.append(currLM.getWordChars(firstElement.getPosition()));
            // look if next elements are boxes too
            while (currParIterator.hasNext()) {
                nextElement = (KnuthElement) currParIterator.next();
                if (nextElement.isBox() && !nextElement.isAuxiliary()) {
                    // a non-auxiliary KnuthBox: append word chars
                    if (currLM != nextElement.getLayoutManager()) {
                        currLM = (InlineLevelLayoutManager) nextElement.getLayoutManager();
                        updateList.add(new Update(currLM, currParIterator.previousIndex()));
                    }
                    // append text to recreate the whole word
                    boxCount++;
                    sbChars.append(currLM.getWordChars(nextElement.getPosition()));
                } else if (!nextElement.isAuxiliary()) {
                    // a non-auxiliary non-box KnuthElement: stop
                    // go back to the last box or auxiliary element
                    currParIterator.previous();
                    break;
                } else {
                    if (currLM != nextElement.getLayoutManager()) {
                        currLM = (InlineLevelLayoutManager) nextElement.getLayoutManager();
                        updateList.add(new Update(currLM, currParIterator.previousIndex()));
                    }
                    // an auxiliary KnuthElement: simply ignore it
                    auxCount++;
                }
            }
            if (log.isTraceEnabled()) {
                log.trace(" Word to hyphenate: " + sbChars.toString());
            }
            // find hyphenation points
            HyphContext hc = getHyphenContext(sbChars);
            // ask each LM to hyphenate its word fragment
            if (hc != null) {
                KnuthElement element = null;
                for (int i = 0; i < (boxCount + auxCount); i++) {
                    currParIterator.previous();
                }
                for (int i = 0; i < (boxCount + auxCount); i++) {
                    element = (KnuthElement) currParIterator.next();
                    if (element.isBox() && !element.isAuxiliary()) {
                        ((InlineLevelLayoutManager) element.getLayoutManager()).hyphenate(element.getPosition(),
                                hc);
                    } else {
                        // nothing to do, element is an auxiliary KnuthElement
                    }
                }
            }
        }
    }
    processUpdates(currPar, updateList);
}

From source file:org.apache.fop.layoutmgr.PageBreakingAlgorithm.java

/**
 * Tries to split the flow of footnotes to put one part on the current page.
 * @param prevListIndex index of the last footnote on the previous page
 * @param prevElementIndex index of the last element of the last footnote
 * @param prevLength total length of footnotes inserted so far
 * @param availableLength available space for footnotes on this page
 * @param canDeferOldFootnotes//  ww w. ja  v  a 2 s  . c o m
 * @return ...
 */
private int getFootnoteSplit(int prevListIndex, int prevElementIndex, int prevLength, int availableLength,
        boolean canDeferOldFootnotes) {
    if (availableLength <= 0) {
        return 0;
    } else {
        // the split should contain a piece of the last footnote
        // together with all previous, not yet inserted footnotes;
        // but if this is not possible, try adding as much content as possible
        int splitLength = 0;
        ListIterator<KnuthElement> noteListIterator;
        KnuthElement element;
        boolean somethingAdded = false;

        // prevListIndex and prevElementIndex points to the last footnote element
        // already placed in a page: advance to the next element
        int listIndex = prevListIndex;
        int elementIndex = prevElementIndex;
        if (elementIndex == getFootnoteList(listIndex).size() - 1) {
            listIndex++;
            elementIndex = 0;
        } else {
            elementIndex++;
        }

        // try adding whole notes
        if (footnotesList.size() - 1 > listIndex) {
            // add the previous footnotes: these cannot be broken or deferred
            if (!canDeferOldFootnotes && newFootnotes && firstNewFootnoteIndex > 0) {
                splitLength = lengthList.get(firstNewFootnoteIndex - 1) - prevLength;
                listIndex = firstNewFootnoteIndex;
                elementIndex = 0;
            }
            // try adding the new footnotes
            while (lengthList.get(listIndex) - prevLength <= availableLength) {
                splitLength = lengthList.get(listIndex) - prevLength;
                somethingAdded = true;
                listIndex++;
                elementIndex = 0;
            }
            // as this method is called only if it is not possible to insert
            // all footnotes, at this point listIndex and elementIndex points to
            // an existing element, the next one we will try to insert
        }

        // try adding a split of the next note
        noteListIterator = getFootnoteList(listIndex).listIterator(elementIndex);

        int prevSplitLength = 0;
        int prevIndex = -1;
        int index = -1;

        while (!(somethingAdded && splitLength > availableLength)) {
            if (!somethingAdded) {
                somethingAdded = true;
            } else {
                prevSplitLength = splitLength;
                prevIndex = index;
            }
            // get a sub-sequence from the note element list
            boolean boxPreceding = false;
            while (noteListIterator.hasNext()) {
                // as this method is called only if it is not possible to insert
                // all footnotes, and we have already tried (and failed) to insert
                // this whole footnote, the while loop will never reach the end
                // of the note sequence
                element = noteListIterator.next();
                if (element.isBox()) {
                    // element is a box
                    splitLength += element.getWidth();
                    boxPreceding = true;
                } else if (element.isGlue()) {
                    // element is a glue
                    if (boxPreceding) {
                        // end of the sub-sequence
                        index = noteListIterator.previousIndex();
                        break;
                    }
                    boxPreceding = false;
                    splitLength += element.getWidth();
                } else {
                    // element is a penalty
                    if (element.getPenalty() < KnuthElement.INFINITE) {
                        // end of the sub-sequence
                        index = noteListIterator.previousIndex();
                        break;
                    }
                }
            }
        }

        // if prevSplitLength is 0, this means that the available length isn't enough
        // to insert even the smallest split of the last footnote, so we cannot end a
        // page here
        // if prevSplitLength is > 0 we can insert some footnote content in this page
        // and insert the remaining in the following one
        //TODO: check this conditional, as the first one is always false...?
        if (!somethingAdded) {
            // there was not enough space to add a piece of the first new footnote
            // this is not a good break
            prevSplitLength = 0;
        } else if (prevSplitLength > 0) {
            // prevIndex is -1 if we have added only some whole footnotes
            footnoteListIndex = (prevIndex != -1) ? listIndex : listIndex - 1;
            footnoteElementIndex = (prevIndex != -1) ? prevIndex
                    : getFootnoteList(footnoteListIndex).size() - 1;
        }
        return prevSplitLength;
    }
}

From source file:org.apache.fop.logging.LoggingElementListObserver.java

/** @see org.apache.fop.layoutmgr.ElementListObserver.Observer */
public void observe(List elementList, String category, String id) {
    Log log = LogFactory.getLog(LoggingElementListObserver.class.getName() + "." + category);
    if (!log.isDebugEnabled()) {
        return;//www .ja v a2 s .c o m
    }
    log.debug(" ");
    int len = (elementList != null ? ElementListUtils.calcContentLength(elementList) : 0);
    log.debug("ElementList: category=" + category + ", id=" + id + ", len=" + len + "mpt");
    if (elementList == null) {
        log.debug("<<empty list>>");
        return;
    }
    ListIterator tempIter = elementList.listIterator();
    ListElement temp;
    while (tempIter.hasNext()) {
        temp = (ListElement) tempIter.next();
        if (temp.isBox()) {
            log.debug(tempIter.previousIndex() + ") " + temp);
        } else if (temp.isGlue()) {
            log.debug(tempIter.previousIndex() + ") " + temp);
        } else {
            log.debug(tempIter.previousIndex() + ") " + temp);
        }
        if (temp.getPosition() != null) {
            log.debug("            " + temp.getPosition());
        }
    }
    log.debug(" ");
}

From source file:org.codehaus.mojo.webminifier.WebMinifierMojo.java

/**
 * Main entry point for the MOJO./* w w  w  .j  av a2  s. co  m*/
 * 
 * @throws MojoExecutionException if there's a problem in the normal course of execution.
 * @throws MojoFailureException if there's a problem with the MOJO itself.
 */
public void execute() throws MojoExecutionException, MojoFailureException {
    // Start off by copying all files over. We'll ultimately remove the js files that we don't need from there, and
    // create new ones in there (same goes for css files and anything else we minify).

    FileUtils.deleteQuietly(destinationFolder);
    try {
        FileUtils.copyDirectory(sourceFolder, destinationFolder);
    } catch (IOException e) {
        throw new MojoExecutionException("Cannot copy file to target folder", e);
    }

    // Process each HTML source file and concatenate into unminified output scripts
    int minifiedCounter = 0;

    // If a split point already exists on disk then we've been through the minification process. As
    // minification can be expensive, we would like to avoid performing it multiple times. Thus storing
    // a set of what we've previously minified enables us.
    Set<File> existingConcatenatedJsResources = new HashSet<File>();
    Set<File> consumedJsResources = new HashSet<File>();

    for (String targetHTMLFile : getArrayOfTargetHTMLFiles()) {
        File targetHTML = new File(destinationFolder, targetHTMLFile);

        // Parse HTML file and locate SCRIPT elements
        DocumentResourceReplacer replacer;
        try {
            replacer = new DocumentResourceReplacer(targetHTML);
        } catch (SAXException e) {
            throw new MojoExecutionException("Problem reading html document", e);
        } catch (IOException e) {
            throw new MojoExecutionException("Problem opening html document", e);
        }

        List<File> jsResources = replacer.findJSResources();

        if (jsSplitPoints == null) {
            jsSplitPoints = new Properties();
        }

        File concatenatedJsResource = null;

        URI destinationFolderUri = destinationFolder.toURI();

        // Split the js resources into two lists: one containing all external dependencies, the other containing
        // project sources. We do this so that project sources can be minified without the dependencies (libraries
        // generally don't need to distribute the dependencies).
        int jsDependencyProjectResourcesIndex;

        if (splitDependencies) {
            List<File> jsDependencyResources = new ArrayList<File>(jsResources.size());
            List<File> jsProjectResources = new ArrayList<File>(jsResources.size());
            for (File jsResource : jsResources) {
                String jsResourceUri = destinationFolderUri.relativize(jsResource.toURI()).toString();
                File jsResourceFile = new File(projectSourceFolder, jsResourceUri);
                if (jsResourceFile.exists()) {
                    jsProjectResources.add(jsResource);
                } else {
                    jsDependencyResources.add(jsResource);
                }
            }

            // Re-constitute the js resource list from dependency resources + project resources and note the index
            // in the list that represents the start of project sources in the list. We need this information later.
            jsDependencyProjectResourcesIndex = jsDependencyResources.size();

            jsResources = jsDependencyResources;
            jsResources.addAll(jsProjectResources);
        } else {
            jsDependencyProjectResourcesIndex = 0;
        }

        // Walk backwards through the script declarations and note what files will map to what split point.
        Map<File, File> jsResourceTargetFiles = new LinkedHashMap<File, File>(jsResources.size());
        ListIterator<File> jsResourcesIter = jsResources.listIterator(jsResources.size());

        boolean splittingDependencies = false;

        while (jsResourcesIter.hasPrevious()) {
            int jsResourceIterIndex = jsResourcesIter.previousIndex();
            File jsResource = jsResourcesIter.previous();

            String candidateSplitPointNameUri = destinationFolderUri.relativize(jsResource.toURI()).toString();
            String splitPointName = (String) jsSplitPoints.get(candidateSplitPointNameUri);

            // If we do not have a split point name and the resource is a dependency of this project i.e. it is not
            // within our src/main folder then we give it a split name of "dependencies". Factoring out dependencies
            // into their own split point is a useful thing to do and will always be required when building
            // libraries.
            if (splitDependencies && splitPointName == null && !splittingDependencies) {
                if (jsResourceIterIndex < jsDependencyProjectResourcesIndex) {
                    splitPointName = Integer.valueOf(++minifiedCounter).toString();
                    splittingDependencies = true;
                }
            }

            // If we have no name and we've not been in here before, then assign an initial name based on a number.
            if (splitPointName == null && concatenatedJsResource == null) {
                splitPointName = Integer.valueOf(++minifiedCounter).toString();
            }

            // We have a new split name so use it for this file and upwards in the script statements until we
            // either hit another split point or there are no more script statements.
            if (splitPointName != null) {
                concatenatedJsResource = new File(destinationFolder, splitPointName + ".js");

                // Note that we've previously created this.
                if (concatenatedJsResource.exists()) {
                    existingConcatenatedJsResources.add(concatenatedJsResource);
                }
            }

            jsResourceTargetFiles.put(jsResource, concatenatedJsResource);
        }

        for (File jsResource : jsResources) {
            concatenatedJsResource = jsResourceTargetFiles.get(jsResource);
            if (!existingConcatenatedJsResources.contains(concatenatedJsResource)) {
                // Concatenate input file onto output resource file
                try {
                    concatenateFile(jsResource, concatenatedJsResource);
                } catch (IOException e) {
                    throw new MojoExecutionException("Problem concatenating JS files", e);
                }

                // Finally, remove the JS resource from the target folder as it is no longer required (we've
                // concatenated it).
                consumedJsResources.add(jsResource);
            }
        }

        // Reduce the list of js resource target files to a distinct set
        LinkedHashSet<File> concatenatedJsResourcesSet = new LinkedHashSet<File>(
                jsResourceTargetFiles.values());
        File[] concatenatedJsResourcesArray = new File[concatenatedJsResourcesSet.size()];
        concatenatedJsResourcesSet.toArray(concatenatedJsResourcesArray);
        List<File> concatenatedJsResources = Arrays.asList(concatenatedJsResourcesArray);

        // Minify the concatenated JS resource files

        if (jsCompressorType != JsCompressorType.NONE) {
            List<File> minifiedJSResources = new ArrayList<File>(concatenatedJsResources.size());

            ListIterator<File> concatenatedJsResourcesIter = concatenatedJsResources
                    .listIterator(concatenatedJsResources.size());
            while (concatenatedJsResourcesIter.hasPrevious()) {
                concatenatedJsResource = concatenatedJsResourcesIter.previous();

                File minifiedJSResource;
                try {
                    String uri = concatenatedJsResource.toURI().toString();
                    int i = uri.lastIndexOf(".js");
                    String minUri;
                    if (i > -1) {
                        minUri = uri.substring(0, i) + "-min.js";
                    } else {
                        minUri = uri;
                    }
                    minifiedJSResource = FileUtils.toFile(new URL(minUri));
                } catch (MalformedURLException e) {
                    throw new MojoExecutionException("Problem determining file URL", e);
                }

                minifiedJSResources.add(minifiedJSResource);

                // If we've not actually performed the minification before... then do so. This is the expensive bit
                // so we like to avoid it if we can.
                if (!existingConcatenatedJsResources.contains(concatenatedJsResource)) {
                    boolean warningsFound;
                    try {
                        warningsFound = minifyJSFile(concatenatedJsResource, minifiedJSResource);
                    } catch (IOException e) {
                        throw new MojoExecutionException("Problem reading/writing JS", e);
                    }

                    logCompressionRatio(minifiedJSResource.getName(), concatenatedJsResource.length(),
                            minifiedJSResource.length());

                    // If there were warnings then the user may want to manually invoke the compressor for further
                    // investigation.
                    if (warningsFound) {
                        getLog().warn("Warnings were found. " + concatenatedJsResource
                                + " is available for your further investigations.");
                    }
                }
            }

            // Update source references
            replacer.replaceJSResources(destinationFolder, targetHTML, minifiedJSResources);
        } else {
            List<File> unminifiedJSResources = new ArrayList<File>(concatenatedJsResources.size());

            ListIterator<File> concatenatedJsResourcesIter = concatenatedJsResources
                    .listIterator(concatenatedJsResources.size());
            while (concatenatedJsResourcesIter.hasPrevious()) {
                concatenatedJsResource = concatenatedJsResourcesIter.previous();
                unminifiedJSResources.add(concatenatedJsResource);
            }

            replacer.replaceJSResources(destinationFolder, targetHTML, unminifiedJSResources);
            getLog().info("Concatenated resources with no compression");
        }

        // Write HTML file to output dir
        try {
            replacer.writeHTML(targetHTML, encoding);
        } catch (TransformerException e) {
            throw new MojoExecutionException("Problem transforming html", e);
        } catch (IOException e) {
            throw new MojoExecutionException("Problem writing html", e);
        }

    }

    // Clean up including the destination folder recursively where directories have nothing left in them.
    for (File consumedJsResource : consumedJsResources) {
        consumedJsResource.delete();
    }
    removeEmptyFolders(destinationFolder);
}

From source file:org.eclipse.jubula.client.core.businessprocess.CompNamesBP.java

/**
 * @param treePath/*  w w w .  jav a2 s.  c om*/
 *            The tree path
 * @param compNameCache
 *            The cache to use in order to resolve Component Name 
 *            references.
 * @param originalName
 *            The GUID of the component name.
 * @param originalCompNameDefiner
 *            The node that is using the component name
 * @return The result containing the component name and the responsible node
 */
private CompNameResult findCompName(List<INodePO> treePath, IComponentNameCache compNameCache,
        String originalName, INodePO originalCompNameDefiner) {

    String currentName = originalName;
    INodePO compNameDefiner = originalCompNameDefiner;
    IComponentNamePO currentNamePo;
    ListIterator<INodePO> it = treePath.listIterator(treePath.size());
    while (it.hasPrevious()) {
        INodePO node = it.previous();
        if (node instanceof IExecTestCasePO) {
            IExecTestCasePO execNode = (IExecTestCasePO) node;
            ICompNamesPairPO pair = null;
            if (!StringUtils.isEmpty(currentName)) {
                pair = execNode.getCompNamesPair(currentName);
            }
            if (pair != null) {
                currentName = pair.getSecondName();
                currentNamePo = compNameCache.getCompNamePo(currentName);
                if (currentNamePo != null) {
                    currentName = currentNamePo.getGuid();
                }
                if (pair.isPropagated()) {
                    int index = it.previousIndex();
                    if (index > -1) {
                        compNameDefiner = treePath.get(index);
                    }
                } else {
                    compNameDefiner = execNode;
                    break;
                }
            }
        }
    }

    return new CompNameResult(currentName, compNameDefiner);
}

From source file:org.netflux.core.task.compose.CombineTask.java

@Override
protected RecordMetadata computeMetadata(String outputPortName, InputPort changedInputPort,
        RecordMetadata newMetadata) {/*  w w w  .  jav a 2  s . c  o m*/
    int insertionPoint = Integer.MAX_VALUE;
    RecordMetadata inputMetadata = this.inputPorts.get("input").getMetadata();

    if (inputMetadata != null && inputMetadata.getFieldCount() > 0) {
        List<FieldMetadata> fieldMetadata = new LinkedList<FieldMetadata>(inputMetadata.getFieldMetadata());
        ListIterator<FieldMetadata> fieldMetadataIterator = fieldMetadata.listIterator();
        while (fieldMetadataIterator.hasNext()) {
            FieldMetadata currentFieldMetadata = fieldMetadataIterator.next();
            if (this.fieldNamesToCombineAsSet.contains(currentFieldMetadata.getName())) {
                insertionPoint = Math.min(insertionPoint, fieldMetadataIterator.previousIndex());
                fieldMetadataIterator.remove();
            }
        }

        this.groupingKeyFieldNames = new ArrayList<String>(new RecordMetadata(fieldMetadata).getFieldNames());

        List<FieldMetadata> combinedMetadata = new LinkedList<FieldMetadata>();
        for (List<String> groupOfCombinedFieldNames : this.getCombinedFieldNames()) {
            Iterator<String> fieldNameToCombineIterator = this.getFieldNamesToCombine().iterator();
            for (String combinedFieldName : groupOfCombinedFieldNames) {
                // FIXME: Do this properly: getFieldMetadata should throw an Exception
                String fieldNameToCombine = fieldNameToCombineIterator.next();
                FieldMetadata currentFieldMetadata = inputMetadata.getFieldMetadata(fieldNameToCombine);
                if (currentFieldMetadata != null) {
                    FieldMetadata currentCombinedMetadata = currentFieldMetadata.clone();
                    currentCombinedMetadata.setName(combinedFieldName);
                    combinedMetadata.add(currentCombinedMetadata);
                } else {
                    combinedMetadata.clear();
                    insertionPoint = fieldMetadata.size();
                    break;
                }
            }
        }

        fieldMetadata.addAll(insertionPoint, combinedMetadata);

        return new RecordMetadata(fieldMetadata);
    } else {
        this.groupingKeyFieldNames = Collections.emptyList();
        List<FieldMetadata> emptyMetadata = Collections.emptyList();
        return new RecordMetadata(emptyMetadata);
    }
}