Example usage for java.util ListIterator nextIndex

List of usage examples for java.util ListIterator nextIndex

Introduction

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

Prototype

int nextIndex();

Source Link

Document

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

Usage

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

/**
 * Creates the element list in BP direction for the broken lines.
 * @param alignment the currently applicable vertical alignment
 * @param context the layout context// ww w  . java2  s. com
 * @return the newly built element list
 */
private List<ListElement> postProcessLineBreaks(int alignment, LayoutContext context) {

    List<ListElement> returnList = new LinkedList<ListElement>();

    int endIndex = -1;
    for (int p = 0; p < knuthParagraphs.size(); p++) {
        // penalty between paragraphs
        if (p > 0) {
            Keep keep = getKeepTogether();
            returnList.add(new BreakElement(new Position(this), keep.getPenalty(), keep.getContext(), context));
        }

        LineLayoutPossibilities llPoss = lineLayoutsList[p];
        KnuthSequence seq = knuthParagraphs.get(p);

        if (!seq.isInlineSequence()) {
            List<ListElement> targetList = new LinkedList<ListElement>();
            ListIterator listIter = seq.listIterator();
            while (listIter.hasNext()) {
                ListElement tempElement;
                tempElement = (ListElement) listIter.next();
                if (tempElement.getLayoutManager() != this) {
                    tempElement.setPosition(notifyPos(new NonLeafPosition(this, tempElement.getPosition())));
                }
                targetList.add(tempElement);
            }
            returnList.addAll(targetList);
        } else if (seq.isInlineSequence() && alignment == EN_JUSTIFY) {
            /* justified vertical alignment (not in the XSL FO recommendation):
               create a multi-layout sequence whose elements will contain
               a conventional Position */
            Position returnPosition = new LeafPosition(this, p);
            createElements(returnList, llPoss, returnPosition);
        } else {
            /* "normal" vertical alignment: create a sequence whose boxes
               represent effective lines, and contain LineBreakPositions */
            int startIndex = 0;
            for (int i = 0; i < llPoss.getChosenLineCount(); i++) {
                if (returnList.size() > 0 && i > 0 //if i==0 break generated above already
                        && i >= fobj.getOrphans() && i <= llPoss.getChosenLineCount() - fobj.getWidows()) {
                    // penalty allowing a page break between lines
                    Keep keep = getKeepTogether();
                    returnList.add(new BreakElement(new LeafPosition(this, p, endIndex), keep.getPenalty(),
                            keep.getContext(), context));
                }
                endIndex = ((LineBreakPosition) llPoss.getChosenPosition(i)).getLeafPos();
                // create a list of the FootnoteBodyLM handling footnotes
                // whose citations are in this line
                List<LayoutManager> footnoteList = new LinkedList<LayoutManager>();
                ListIterator<KnuthElement> elementIterator = seq.listIterator(startIndex);
                while (elementIterator.nextIndex() <= endIndex) {
                    KnuthElement element = elementIterator.next();
                    if (element instanceof KnuthInlineBox && ((KnuthInlineBox) element).isAnchor()) {
                        footnoteList.add(((KnuthInlineBox) element).getFootnoteBodyLM());
                    } else if (element instanceof KnuthBlockBox) {
                        footnoteList.addAll(((KnuthBlockBox) element).getFootnoteBodyLMs());
                    }
                }
                startIndex = endIndex + 1;
                LineBreakPosition lbp = (LineBreakPosition) llPoss.getChosenPosition(i);
                returnList.add(new KnuthBlockBox(lbp.lineHeight + lbp.spaceBefore + lbp.spaceAfter,
                        footnoteList, lbp, false));
            }
        }
    }

    return returnList;
}

From source file:com.apptentive.android.sdk.module.engagement.interaction.fragment.MessageCenterFragment.java

public void updateMessageSentStates() {
    dateStampsSeen.clear();//from w w  w  . ja  va2 s. co m
    MessageCenterUtil.CompoundMessageCommonInterface lastSent = null;
    Set<String> uniqueNonce = new HashSet<String>();
    int removedItems = 0;
    ListIterator<MessageCenterListItem> listItemIterator = listItems.listIterator();
    while (listItemIterator.hasNext()) {
        int adapterMessagePosition = listItemIterator.nextIndex() - removedItems;
        MessageCenterListItem message = listItemIterator.next();
        if (message instanceof ApptentiveMessage) {
            /* Check if there is any duplicate messages and remove if found.
            * add() of a Set returns false if the element already exists.
             */
            if (!uniqueNonce.add(((ApptentiveMessage) message).getNonce())) {
                listItemIterator.remove();
                messageCenterRecyclerViewAdapter.notifyItemRemoved(adapterMessagePosition);
                removedItems++;
                continue;
            }
            // Update timestamps
            ApptentiveMessage apptentiveMessage = (ApptentiveMessage) message;
            Double sentOrReceivedAt = apptentiveMessage.getCreatedAt();
            String dateStamp = createDatestamp(sentOrReceivedAt);
            if (dateStamp != null) {
                if (dateStampsSeen.add(dateStamp)) {
                    if (apptentiveMessage.setDatestamp(dateStamp)) {
                        messageCenterRecyclerViewAdapter.notifyItemChanged(adapterMessagePosition);
                    }
                } else {
                    if (apptentiveMessage.clearDatestamp()) {
                        messageCenterRecyclerViewAdapter.notifyItemChanged(adapterMessagePosition);
                    }
                }
            }

            //Find last sent
            if (apptentiveMessage.isOutgoingMessage()) {
                if (sentOrReceivedAt != null && sentOrReceivedAt > Double.MIN_VALUE) {
                    lastSent = (MessageCenterUtil.CompoundMessageCommonInterface) apptentiveMessage;
                    lastSent.setLastSent(false);
                }

            }
        }
    }

    if (lastSent != null) {
        lastSent.setLastSent(true);
    }
}

From source file:org.openconcerto.openoffice.ODSingleXMLDocument.java

/**
 * Fusionne les corps.//from   ww  w  .  j  av a 2 s.c  o  m
 * 
 * @param where the element where to add the main content, <code>null</code> meaning at the root
 *        of the body.
 * @param index the content index inside <code>where</code>, -1 meaning at the end.
 * @param doc le document  fusionner avec celui-ci.
 * @throws JDOMException
 */
private void mergeBody(Element where, int index, ODSingleXMLDocument doc) throws JDOMException {
    final Element thisBody = this.getBody();
    final Map<Tuple2<Namespace, String>, ContentPart> parts = ELEMS_PARTS.get(getVersion());

    // find where to add
    final Element nonNullWhere = where != null ? where : thisBody;
    if (nonNullWhere == thisBody) {
        // don't add in prologue or epilogue (ATTN the caller passed the index in reference to
        // the existing body but it might change and thus the index might need correction)
        index = getValidIndex(parts, thisBody, index);
    } else {
        // check that the element is rooted in the main part
        final Element movedChild = JDOMUtils.getAncestor(nonNullWhere, new IPredicate<Element>() {
            @Override
            public boolean evaluateChecked(Element input) {
                return input.getParent() == thisBody;
            }
        });
        if (movedChild == null)
            throw new IllegalStateException("not adding in body : " + nonNullWhere);
        final ContentPart contentPart = getPart(parts, movedChild);
        if (contentPart != ContentPart.MAIN)
            throw new IllegalStateException("not adding in main : " + contentPart + " ; " + nonNullWhere);
    }

    final ChildCreator childCreator = ChildCreator.createFromSets(thisBody, ELEMS_ORDER.get(getVersion()));
    int prologueAddedCount = 0;
    final Element otherBody = doc.getBody();
    // split doc body in to three parts to keep non-elements
    final Point[] bounds = getBounds(parts, otherBody, false);
    @SuppressWarnings("unchecked")
    final List<Content> otherContent = otherBody.getContent();
    // prologue and epilogue have small and bounded size
    final List<Content> mainElements = new ArrayList<Content>(otherContent.size());
    final ListIterator<Content> listIter = otherContent.listIterator();
    for (final ContentPart part : ContentPart.values()) {
        final Point partBounds = bounds[part.ordinal()];
        final int partEnd = partBounds.y;
        while (listIter.nextIndex() < partEnd) {
            assert listIter.hasNext() : "wrong bounds";
            final Content c = listIter.next();
            if (c instanceof Element) {
                final Element bodyChild = (Element) c;
                if (part == ContentPart.PROLOGUE) {
                    final int preSize = thisBody.getContentSize();
                    final String childName = bodyChild.getName();
                    if (childName.equals("forms")) {
                        final Element elem = (Element) bodyChild.clone();
                        // TODO prefix xml:id and their draw:control references
                        this.prefix(elem, true);
                        childCreator.getChild(bodyChild, true).addContent(elem.removeContent());
                    } else if (childName.equals("variable-decls") || childName.equals("sequence-decls")
                            || childName.equals("user-field-decls")) {
                        final Element elem = (Element) bodyChild.clone();
                        // * user fields are global to a document, they do not vary across it.
                        // Hence they are initialized at declaration
                        // * variables are not initialized at declaration
                        detachDuplicate(elem);
                        this.prefix(elem, true);
                        childCreator.getChild(bodyChild, true).addContent(elem.removeContent());
                    } else {
                        Log.get().fine("Ignoring in " + part + " : " + bodyChild);
                    }
                    final int postSize = thisBody.getContentSize();
                    prologueAddedCount += postSize - preSize;
                } else if (part == ContentPart.MAIN) {
                    mainElements.add(this.prefix((Element) bodyChild.clone(), true));
                } else if (part == ContentPart.EPILOGUE) {
                    Log.get().fine("Ignoring in " + part + " : " + bodyChild);
                }
            } else if (part == ContentPart.MAIN) {
                mainElements.add((Content) c.clone());
            } else {
                Log.get().finer("Ignoring non-element in " + part);
            }
        }
    }

    if (nonNullWhere == thisBody) {
        assert index >= 0;
        index += prologueAddedCount;
        assert index >= 0 && index <= thisBody.getContentSize();
    }
    if (index < 0)
        nonNullWhere.addContent(mainElements);
    else
        nonNullWhere.addContent(index, mainElements);
}

From source file:co.cask.cdap.common.conf.Configuration.java

private <T> void toString(List<T> resources, StringBuilder sb) {
    ListIterator<T> i = resources.listIterator();
    while (i.hasNext()) {
        if (i.nextIndex() != 0) {
            sb.append(", ");
        }//from  w w w  .  j  a  va 2  s  .co  m
        sb.append(i.next());
    }
}

From source file:org.shareok.data.dspacemanager.DspaceApiHandlerImpl.java

/**
 * Load saf package information and import it into DSpace repository
 * /*w w w.j a v  a  2 s .  com*/
 * @return : the mapping of the imported information to DSpace items
 */
@Override
public Map<String, List<String>> loadItemsFromSafPackage() {

    String collectionHandle = job.getCollectionId();
    String safPath = job.getFilePath();
    if (DocumentProcessorUtil.isEmptyString(dspaceApiUrl)) {
        dspaceApiUrl = RedisUtil.getServerDaoInstance().findServerById(job.getServerId()).getAddress();
    }

    Map<String, List<String>> importResults = new HashMap<>();

    if (DocumentProcessorUtil.isEmptyString(token)) {
        getTokenFromServer();
        if (DocumentProcessorUtil.isEmptyString(token)) {
            try {
                throw new NoExistingApiTokenException("Cannot get useful token!");
            } catch (NoExistingApiTokenException ex) {
                logger.error(ex.getMessage());
                return null;
            }
        }
    }

    try {
        File safFile = new File(safPath);
        if (safPath.endsWith(".zip")) {
            String newPath = FileZipper.unzipToDirectory(safPath);
            if (null == newPath) {
                throw new ErrorUnzipSafPackageException("Cannot unzip the saf package at " + safPath);
            }
            // Change the path to be the unzipped folder
            //                safPath = DocumentProcessorUtil.getFileNameWithoutExtension(safPath);
            safFile = new File(newPath);
        }
        if (safFile.isDirectory()) {
            mainLoop: for (File file : safFile.listFiles()) {
                if (null != file && file.isDirectory()) {

                    File[] fileList = file.listFiles();
                    boolean containsContentsFile = false;
                    boolean containsMetadataFile = false;

                    List<File> metadataFileList = new ArrayList<>();
                    File contentFile = null;

                    for (File itemFile : fileList) {

                        if (null == itemFile) {
                            continue;
                        }

                        String fileName = itemFile.getName();
                        if ("contents".equals(fileName)) {
                            containsContentsFile = true;
                            contentFile = itemFile;
                        } else if (METADATA_FILE_NAMES_LIST.contains(fileName.replaceAll(".xml", ""))) {
                            // Check if there are some duplicates based on doi
                            if (fileName.contains("dublin")) {
                                String doi = findDoiFromDublin(itemFile.getAbsolutePath());
                                if (null != doi && checkDuplicatesByDoi(doi, collectionHandle, dspaceApiUrl)) {
                                    logger.debug("Duplication detected:in collection " + collectionHandle
                                            + " there has already been an item with doi=" + doi);
                                    output += "Duplication detected:in collection \"+collectionHandle+\" there has already been an item with doi="
                                            + doi + ".\n\n";
                                    continue mainLoop;
                                }
                            }
                            containsMetadataFile = true;
                            metadataFileList.add(itemFile);
                        }
                    }
                    if (containsContentsFile == true && containsMetadataFile == true) {
                        // Create the new item now:
                        Map newItemInfo = createEmptyItem(getObjectIdByHandler(collectionHandle, dspaceApiUrl));
                        String newItemId = String.valueOf(newItemInfo.get("id"));
                        String newItemHandle = (String) newItemInfo.get("handle");
                        logger.debug("A new item with handle = " + newItemHandle
                                + " has been added to collection " + collectionHandle + ".");
                        output += "A new item with handle = " + newItemHandle + " has been added to collection "
                                + collectionHandle + ".\n\n";
                        mapping += file.getName() + "   " + newItemHandle + "\n";

                        // Add the metadata to the new item:
                        String[] paths = new String[metadataFileList.size()];
                        ListIterator metadataIt = metadataFileList.listIterator();
                        while (metadataIt.hasNext()) {
                            File metadataFile = (File) metadataIt.next();
                            paths[metadataIt.nextIndex() - 1] = metadataFile.getAbsolutePath();
                        }
                        Map<String, String> metadataStrings = getMetadataFromXmlFiles(paths);
                        for (String path : metadataStrings.keySet()) {
                            String metadata = metadataStrings.get(path);
                            logger.debug(" adding metadata file " + metadata + " now with file name : "
                                    + file.getName());
                            output += " adding metadata file " + metadata + " now with file name : "
                                    + file.getName() + "\n\n";
                            try {
                                String metadataInfo = addItemMetadata(newItemId, metadata);
                                if (null == metadataInfo || metadataInfo.equals("")) {
                                    if (null == importResults.get("metadata-imported")) {
                                        importResults.put("metadata-imported", new ArrayList<String>());
                                    }
                                    List metadataUnimportedList = (ArrayList) importResults
                                            .get("metadata-imported");
                                    metadataUnimportedList.add(newItemId + "---" + path);
                                    logger.debug(
                                            "Failed to add the metadata into item " + newItemHandle + ".\n");
                                    output += "Failed to add the metadata into item " + newItemHandle + ".\n\n";
                                } else {
                                    if (null == importResults.get("metadata-imported")) {
                                        importResults.put("metadata-imported", new ArrayList<String>());
                                    }
                                    List metadataImportedList = (ArrayList) importResults
                                            .get("metadata-imported");
                                    metadataImportedList.add(newItemId + "---" + path);
                                    logger.debug("A new set of metadata entries have been added to the item "
                                            + newItemHandle + ". \n");
                                    output += "A new set of metadata entries have been added to the item "
                                            + newItemHandle + ". \n\n";
                                }
                            } catch (Exception ex) {
                                if (null == importResults.get("metadata-imported")) {
                                    importResults.put("metadata-imported", new ArrayList<String>());
                                }
                                List metadataUnimportedList = (ArrayList) importResults
                                        .get("metadata-imported");
                                metadataUnimportedList.add(newItemId + "---" + path);
                                logger.debug("Failed to add metadata into item " + newItemHandle + "\n"
                                        + ex.getMessage());
                                output += "Failed to add metadata into item " + newItemHandle + "\n"
                                        + ex.getMessage() + "\n\n";
                            }
                        }

                        List bitstreamFileList = DocumentProcessorUtil
                                .readTextFileIntoList(contentFile.getAbsolutePath());
                        ListIterator it = bitstreamFileList.listIterator();
                        while (it.hasNext()) {
                            String bitstreamFileName = (String) it.next();
                            File bitstreamFile = new File(
                                    file.getAbsoluteFile() + File.separator + bitstreamFileName);
                            if (!bitstreamFile.exists()) {
                                logger.debug("The bitstream file " + bitstreamFileName
                                        + " does not exist in the saf package " + safPath + "!\n");
                                output += "The bitstream file " + bitstreamFileName
                                        + " does not exist in the saf package " + safPath + "!\n\n";
                            } else {
                                String newName = bitstreamFile.getName().replace(" ", "_");
                                try {
                                    Map bitstreamInfo = addItemBitstream(newItemId,
                                            bitstreamFile.getAbsolutePath(), newName, newName);
                                    if (null != bitstreamInfo) {
                                        if (null == importResults.get("bitstream-imported")) {
                                            importResults.put("bitstream-imported", new ArrayList<String>());
                                        }
                                        List bitstreamImportedList = (ArrayList) importResults
                                                .get("bitstream-imported");
                                        bitstreamImportedList
                                                .add(newItemId + "---" + bitstreamFile.getAbsoluteFile());
                                        logger.debug("A new bitstream file " + bitstreamFileName + " with link "
                                                + ((String) bitstreamInfo.get("retrieveLink"))
                                                + " has been added to the item " + newItemHandle + ". \n");
                                        output += "A new bitstream file " + bitstreamFileName + " with link "
                                                + ((String) bitstreamInfo.get("retrieveLink"))
                                                + " has been added to the item " + newItemHandle + ". \n\n";
                                    } else {
                                        if (null == importResults.get("bitstream-unimported")) {
                                            importResults.put("bitstream-unimported", new ArrayList<String>());
                                        }
                                        List bitstreamUnimportedList = (ArrayList) importResults
                                                .get("bitstream-unimported");
                                        bitstreamUnimportedList
                                                .add(newItemId + "---" + bitstreamFile.getAbsoluteFile());
                                        logger.debug("Failed to add the bitstream file " + bitstreamFileName
                                                + " into item " + newItemHandle + ".\n");
                                        output += "Failed to add the bitstream file " + bitstreamFileName
                                                + " into item " + newItemHandle + ".\n\n";
                                    }
                                } catch (Exception ex) {
                                    if (null == importResults.get("bitstream-unimported")) {
                                        importResults.put("bitstream-unimported", new ArrayList<String>());
                                    }
                                    List bitstreamUnimportedList = (ArrayList) importResults
                                            .get("bitstream-unimported");
                                    bitstreamUnimportedList
                                            .add(newItemId + "---" + bitstreamFile.getAbsoluteFile());
                                    logger.debug("Failed to add the bitstream file " + bitstreamFileName
                                            + " into item " + newItemHandle + ".\n" + ex.getMessage());
                                    output += "Failed to add the bitstream file " + bitstreamFileName
                                            + " into item " + newItemHandle + ".\n" + ex.getMessage() + "\n\n";
                                }
                            }
                        }
                    } else {
                        logger.debug(
                                "This saf package is missing either the contents file or the metadata files.\n");
                        output += "This saf package is missing either the contents file or the metadata files.\n\n";
                        throw new SafPackageMissingFileException("Saf package at " + safPath
                                + " either the contents file or the metadata files are missing!");
                    }
                }
            }
        } else {
            throw new SafPackagePathErrorException("Saf package path is not a directory");
        }

        // Due to various reasons, some metadata and/or bitstreams cannot be added and are given second chance here:
        List metadataUnimportedList = (ArrayList) importResults.get("metadata-unimported");
        if (null != metadataUnimportedList && metadataUnimportedList.size() > 0) {
            for (Iterator<String> iterator = metadataUnimportedList.iterator(); iterator.hasNext();) {
                String[] values = ((String) iterator.next()).split("---");
                logger.debug("Second try to add metadata into " + values[0] + " with data " + values[1]);
                output += "Second try to add metadata into " + values[0] + " with data " + values[1] + "\n\n";
                try {
                    String metadataInfo = addItemMetadata(values[0], values[1]);
                    if (null != metadataInfo) {
                        iterator.remove();
                        logger.debug("Second try: sucessfully added metadata into item " + values[0]
                                + " with data " + values[1]);
                        output += "Second try: sucessfully added metadata into item " + values[0]
                                + " with data " + values[1] + "\n\n";
                    } else {
                        logger.debug("Second try: failed to add metadata into item " + values[0] + " with data "
                                + values[1]);
                        output += "Second try: failed to add metadata into item " + values[0] + " with data "
                                + values[1] + "\n\n";
                    }
                } catch (Exception ex) {
                    logger.debug("Second try: failed to add metadata into item " + values[0] + " with data "
                            + values[1] + "\n" + ex.getMessage());
                    output += "Second try: failed to add metadata into item " + values[0] + " with data "
                            + values[1] + "\n" + ex.getMessage() + "\n\n";
                }
            }
        }

        List bitstreamUnimportedList = (ArrayList) importResults.get("bitstream-unimported");
        if (null != bitstreamUnimportedList && bitstreamUnimportedList.size() > 0) {
            //                for (Object bitstreamUnimportedList1 : bitstreamUnimportedList) {
            for (Iterator<String> iterator = metadataUnimportedList.iterator(); iterator.hasNext();) {
                String[] values = ((String) iterator.next()).split("---");
                String name = new File(values[1]).getName().replace(" ", "_");
                logger.debug("Second try to add bitstream into " + values[0] + " with path " + values[1]);
                output += "Second try to add bitstream into " + values[0] + " with path " + values[1] + "\n\n";
                try {
                    Map bitstreamInfo = addItemBitstream(values[0], values[1], name, name);
                    if (null != bitstreamInfo) {
                        iterator.remove();
                        logger.debug("Second try: sucessfully added bitstream into item " + values[0]
                                + " with path " + values[1]);
                        output += "Second try: sucessfully added bitstream into item " + values[0]
                                + " with path " + values[1] + "\n\n";
                    } else {
                        logger.debug("Second try: failed to add bitstream into item " + values[0]
                                + " with path " + values[1]);
                        output += "Second try: failed to add bitstream into item " + values[0] + " with path "
                                + values[1] + "\n\n";
                    }
                } catch (Exception ex) {
                    logger.debug("Second try: failed to add bitstream into item " + values[0] + " with path "
                            + values[1] + "\n" + ex.getMessage());
                    output += "Second try: failed to add bitstream into item " + values[0] + " with path "
                            + values[1] + "\n" + ex.getMessage() + "\n\n";
                }
            }
        }

    } catch (SafPackagePathErrorException | SafPackageMissingFileException ex) {
        output += "Saf package is not valid!\n" + ex.getMessage() + "\n\n";
        logger.error("Cannot create new items with saf package path: " + safPath, ex);
    } catch (ErrorUnzipSafPackageException ex) {
        Logger.getLogger(DspaceApiHandlerImpl.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        DocumentProcessorUtil.outputStringToFile(mapping,
                DocumentProcessorUtil.getFileContainerPath(reportFilePath) + File.separator + "mapfile");
        DocumentProcessorUtil.outputStringToFile(output, reportFilePath);
    }

    return importResults;
}

From source file:org.shareok.data.dspacemanager.DspaceApiHandlerImpl.java

@Override
public Map<String, List<String>> loadItemsFromSafPackage(String safPath, String collectionHandle,
        String dspaceApiUrl) {//w w  w  .  j a va2s .com
    Map<String, List<String>> importResults = new HashMap<>();
    this.dspaceApiUrl = dspaceApiUrl;
    BufferedWriter loggingForUserWriter = null;
    BufferedWriter mapWriter = null;
    String message;

    if (DocumentProcessorUtil.isEmptyString(token)) {
        getTokenFromServer();
        if (DocumentProcessorUtil.isEmptyString(token)) {
            try {
                throw new NoExistingApiTokenException("Cannot get useful token!");
            } catch (NoExistingApiTokenException ex) {
                logger.error(ex.getMessage());
                return null;
            }
        }
    }

    try {
        try {
            loggingForUserWriter = DataHandlersUtil.getWriterLoggingForUserFile(
                    DataHandlersUtil.CURRENT_TASK_ID, DataHandlersUtil.CURRENT_TASK_TYPE);
        } catch (IOException ex) {
            logger.error("Cannot get the output file writer", ex);
            return null;
        }

        loggingForUserWriter.write(
                "\n\n==================================================\n\nStart to import the items in the SAF package.\n\n\n");

        try {
            File mapFile = new File(
                    DocumentProcessorUtil.getFileContainerPath(reportFilePath) + File.separator + "mapfile");
            if (!mapFile.exists()) {
                mapFile.createNewFile();
            }
            mapWriter = new BufferedWriter(new FileWriter(mapFile));
        } catch (IOException ex) {
            logger.error("Cannot get the output file writer", ex);
            loggingForUserWriter.write(
                    "Cannot generate the map file, task dismissed. Please contact the relative personnel.\n");
            return null;
        }
        File safFile = new File(safPath);
        if (safPath.endsWith(".zip")) {
            String newPath = FileZipper.unzipToDirectory(safPath);
            if (null == newPath) {
                loggingForUserWriter
                        .write("The SAF package has problem, please contact the relative personnel.\n");
                throw new ErrorUnzipSafPackageException("Cannot unzip the saf package at " + safPath);
            }
            // Change the path to be the unzipped folder
            //                safPath = DocumentProcessorUtil.getFileNameWithoutExtension(safPath);
            safFile = new File(newPath);
        }
        if (safFile.isDirectory()) {
            mainLoop: for (File file : safFile.listFiles()) {
                if (null != file && file.isDirectory()) {

                    File[] fileList = file.listFiles();
                    boolean containsContentsFile = false;
                    boolean containsMetadataFile = false;

                    List<File> metadataFileList = new ArrayList<>();
                    File contentFile = null;
                    String doi = "";

                    for (File itemFile : fileList) {

                        if (null == itemFile) {
                            continue;
                        }

                        String fileName = itemFile.getName();
                        if ("contents".equals(fileName)) {
                            containsContentsFile = true;
                            contentFile = itemFile;
                        } else if (METADATA_FILE_NAMES_LIST.contains(fileName.replaceAll(".xml", ""))) {
                            // Check if there are some duplicates based on doi
                            if (fileName.contains("dublin")) {
                                doi = findDoiFromDublin(itemFile.getAbsolutePath());
                                if (null != doi && checkDuplicatesByDoi(doi, collectionHandle, dspaceApiUrl)) {
                                    message = "Duplication detected: collection " + collectionHandle
                                            + " has already had an item with doi=" + doi;
                                    logger.debug(message);
                                    System.out.println(message + ".\n\n\n");
                                    loggingForUserWriter.write(message + ".\n\n\n");
                                    loggingForUserWriter.write("Item with doi:" + doi
                                            + " has been processed.\n\n==================================================\n\n");
                                    continue mainLoop;
                                }
                            }
                            containsMetadataFile = true;
                            metadataFileList.add(itemFile);
                        }
                    }
                    if (containsContentsFile == true && containsMetadataFile == true) {
                        String newItemId;
                        String newItemHandle;
                        // Create the new item now:
                        try {
                            String collectionId = getObjectIdByHandler(collectionHandle, dspaceApiUrl);
                            if (DocumentProcessorUtil.isEmptyString(collectionId)) {
                                throw new Exception(
                                        "Cannot get collection ID from handler " + collectionHandle + "!");
                            }
                            Map newItemInfo = createEmptyItem(
                                    getObjectIdByHandler(collectionHandle, dspaceApiUrl));
                            newItemId = String.valueOf(newItemInfo.get("id"));
                            newItemHandle = (String) newItemInfo.get("handle");
                            message = "A new item with handle = " + newItemHandle
                                    + " has been added to collection " + collectionHandle + ".\n\n";
                            logger.debug(message);
                            System.out.println(message);
                            loggingForUserWriter.write(message);
                            mapWriter.write(file.getName() + "   " + newItemHandle + "\n");
                        } catch (Exception ex) {
                            message = "Cannot create the new item with collection handler " + collectionHandle
                                    + ".\nItem with doi=" + doi + " is not added.";
                            logger.error(message, ex);
                            System.out.println(message + "\n\n\n");
                            loggingForUserWriter.write(message + "\n\n\n");
                            continue;
                        }

                        // Add the metadata to the new item:
                        String[] paths = new String[metadataFileList.size()];
                        ListIterator metadataIt = metadataFileList.listIterator();
                        while (metadataIt.hasNext()) {
                            File metadataFile = (File) metadataIt.next();
                            paths[metadataIt.nextIndex() - 1] = metadataFile.getAbsolutePath();
                        }
                        Map<String, String> metadataStrings = getMetadataFromXmlFiles(paths);
                        for (String path : metadataStrings.keySet()) {
                            String metadata = metadataStrings.get(path);
                            message = "Adding metadata file " + metadata + " now with file name : "
                                    + file.getName();
                            logger.debug(message);
                            System.out.println(message + "\n\n");
                            loggingForUserWriter.write("Start to add metadata for item doi:" + doi + "\n");

                            try {
                                String metadataInfo = addItemMetadata(newItemId, metadata);
                                if (null == metadataInfo || metadataInfo.equals("")) {
                                    if (null == importResults.get("metadata-imported")) {
                                        importResults.put("metadata-imported", new ArrayList<String>());
                                    }
                                    List metadataUnimportedList = (ArrayList) importResults
                                            .get("metadata-imported");
                                    metadataUnimportedList.add(newItemId + "---" + path);
                                    message = "Failed to add the metadata into item " + newItemHandle + ".\n\n";
                                    logger.debug(message);
                                    System.out.println(message);
                                    loggingForUserWriter.write(message);
                                } else {
                                    if (null == importResults.get("metadata-imported")) {
                                        importResults.put("metadata-imported", new ArrayList<String>());
                                    }
                                    List metadataImportedList = (ArrayList) importResults
                                            .get("metadata-imported");
                                    metadataImportedList.add(newItemId + "---" + path);
                                    message = "A new set of metadata entries have been added to the item "
                                            + newItemHandle + ". \n\n";
                                    logger.debug(message);
                                    System.out.println(message);
                                    loggingForUserWriter.write(message);
                                }
                            } catch (Exception ex) {
                                if (null == importResults.get("metadata-imported")) {
                                    importResults.put("metadata-imported", new ArrayList<String>());
                                }
                                List metadataUnimportedList = (ArrayList) importResults
                                        .get("metadata-imported");
                                metadataUnimportedList.add(newItemId + "---" + path);
                                message = "Failed to add metadata into item " + newItemHandle + "\n"
                                        + ex.getMessage();
                                logger.debug(message);
                                System.out.println(message + "\n\n");
                                loggingForUserWriter.write(message + "\n\n");
                            }
                        }

                        List bitstreamFileList = DocumentProcessorUtil
                                .readTextFileIntoList(contentFile.getAbsolutePath());
                        ListIterator it = bitstreamFileList.listIterator();
                        while (it.hasNext()) {
                            String bitstreamFileName = (String) it.next();
                            File bitstreamFile = new File(
                                    file.getAbsoluteFile() + File.separator + bitstreamFileName);
                            if (!bitstreamFile.exists()) {
                                message = "The bitstream file " + bitstreamFileName
                                        + " does not exist in the saf package " + safPath + "!\n";
                                logger.debug(message);
                                System.out.println(message + "!\n\n");
                                loggingForUserWriter.write(message + "!\n\n");
                            } else {
                                String newName = bitstreamFile.getName().replace(" ", "_");
                                try {
                                    Map bitstreamInfo = addItemBitstream(newItemId,
                                            bitstreamFile.getAbsolutePath(), newName, newName);
                                    if (null != bitstreamInfo) {
                                        if (null == importResults.get("bitstream-imported")) {
                                            importResults.put("bitstream-imported", new ArrayList<String>());
                                        }
                                        List bitstreamImportedList = (ArrayList) importResults
                                                .get("bitstream-imported");
                                        bitstreamImportedList
                                                .add(newItemId + "---" + bitstreamFile.getAbsoluteFile());
                                        message = "A new bitstream file " + bitstreamFileName
                                                + " has been added to the item " + newItemHandle + ".\n\n";
                                        logger.debug(message);
                                        System.out.println(message);
                                        loggingForUserWriter.write(message);
                                    } else {
                                        if (null == importResults.get("bitstream-unimported")) {
                                            importResults.put("bitstream-unimported", new ArrayList<String>());
                                        }
                                        List bitstreamUnimportedList = (ArrayList) importResults
                                                .get("bitstream-unimported");
                                        bitstreamUnimportedList
                                                .add(newItemId + "---" + bitstreamFile.getAbsoluteFile());
                                        message = "Cannot add the bitstream!";
                                        throw new Exception(message);
                                    }
                                } catch (Exception ex) {
                                    if (null == importResults.get("bitstream-unimported")) {
                                        importResults.put("bitstream-unimported", new ArrayList<String>());
                                    }
                                    List bitstreamUnimportedList = (ArrayList) importResults
                                            .get("bitstream-unimported");
                                    bitstreamUnimportedList
                                            .add(newItemId + "---" + bitstreamFile.getAbsoluteFile());
                                    message = "Failed to add the bitstream file " + bitstreamFileName
                                            + " into item " + newItemHandle + ".\n";
                                    logger.debug(message, ex);
                                    ex.printStackTrace();
                                    loggingForUserWriter.write(message);
                                }
                            }
                        }
                    } else {
                        message = "This saf package is missing either the contents file or the metadata files.\n\n";
                        logger.debug(message);
                        System.out.println(message);
                        loggingForUserWriter.write(message);
                        //throw new SafPackageMissingFileException("Saf package at " + safPath + " either the contents file or the metadata files are missing!");
                    }
                    loggingForUserWriter.write("Item with doi:" + doi
                            + " has been processed.\n\n==================================================\n\n");
                }
            }
        } else {
            message = "This SAF package is not a directory.\n\n\n";
            logger.debug(message);
            System.out.println(message);
            loggingForUserWriter.write(message);
            throw new SafPackagePathErrorException(message);
        }

        // Due to various reasons, some metadata and/or bitstreams cannot be added and are given second chance here:
        List metadataUnimportedList = (ArrayList) importResults.get("metadata-unimported");
        if (null != metadataUnimportedList && metadataUnimportedList.size() > 0) {
            for (Iterator<String> iterator = metadataUnimportedList.iterator(); iterator.hasNext();) {
                String[] values = ((String) iterator.next()).split("---");
                message = "Second try to add metadata into " + values[0] + " with data " + values[1];
                logger.debug(message);
                System.out.println(message + "\n\n");
                loggingForUserWriter.write(message + "\n\n");
                try {
                    String metadataInfo = addItemMetadata(values[0], values[1]);
                    if (null != metadataInfo) {
                        iterator.remove();
                        message = "Second try: sucessfully added metadata into item " + values[0]
                                + " with data " + values[1];
                        logger.debug(message);
                        System.out.println(message + "\n\n");
                        loggingForUserWriter.write(message + "\n\n");
                    } else {
                        throw new Exception();
                    }
                } catch (Exception ex) {
                    message = "Second try: failed to add metadata into item " + values[0] + " with data "
                            + values[1] + "\n" + ex.getMessage();
                    logger.debug(message);
                    System.out.println(message + "\n\n");
                    loggingForUserWriter.write(message + "\n\n");
                }
            }
        }

        List bitstreamUnimportedList = (ArrayList) importResults.get("bitstream-unimported");
        if (null != bitstreamUnimportedList && bitstreamUnimportedList.size() > 0) {
            //                for (Object bitstreamUnimportedList1 : bitstreamUnimportedList) {
            for (Iterator<String> iterator = bitstreamUnimportedList.iterator(); iterator.hasNext();) {
                String[] values = ((String) iterator.next()).split("---");
                String name = new File(values[1]).getName().replace(" ", "_");
                message = "Second try to add bitstream into " + values[0] + " with path " + values[1];
                logger.debug(message);
                System.out.println(message + "\n\n");
                loggingForUserWriter.write(message + "\n\n");
                try {
                    Map bitstreamInfo = addItemBitstream(values[0], values[1], name, name);
                    if (null != bitstreamInfo) {
                        iterator.remove();
                        message = "Second try: sucessfully added bitstream into item " + values[0]
                                + " with path " + values[1];
                        logger.debug(message);
                        System.out.println(message + "\n\n");
                        loggingForUserWriter.write(message + "\n\n");
                    } else {
                        message = "Second try: failed to add bitstream into item " + values[0] + " with path "
                                + values[1];
                        logger.debug(message);
                        System.out.println(message + "\n\n");
                        loggingForUserWriter.write(message + "\n\n");
                        throw new Exception(message);
                    }
                } catch (Exception ex) {
                    logger.error(ex);
                }
            }
        }

    } catch (SafPackagePathErrorException ex) {
        message = "Saf package is not valid!\n" + ex.getMessage();
        System.out.println(message + "\n\n");
        logger.error("Cannot create new items with saf package path: " + safPath, ex);
    } catch (NullPointerException | ErrorUnzipSafPackageException | IOException ex) {
        logger.error(ex);
    } finally {
        if (null != loggingForUserWriter) {
            try {
                loggingForUserWriter.flush();
            } catch (IOException ex) {
                logger.error("Cannot close the output file writer!");
            }
        }
        if (null != mapWriter) {
            try {
                mapWriter.flush();
                mapWriter.close();
            } catch (IOException ex) {
                logger.error("Cannot close the map file writer!");
            }
        }
    }
    return importResults;
}

From source file:org.squale.squalecommon.enterpriselayer.applicationcomponent.display.ResultsApplicationComponentAccess.java

/**
 * Ajoute  pResultDTOs les ResultDTO correspondant.Recupere pour tous les audits les ResultsDTO au format composant
 * en fonction des tres, et les ajoute a la liste de ResultsDTO  renvoyer  l'utilisateur.
 * //from   w ww . j  a v  a 2s .  c o  m
 * @param pResultDTOs la liste de ResultDTO donnant les projets
 * @param pCurrentAudits liste des AuditDTO concerns
 * @param pChildren enfants dont on veut les rsultats parametres des facades MeasureFacade et QResultFacade
 * @return une liste de ResultDTO au mme format que dans la methode getApplicationResults()
 * @throws JrafEnterpriseException Exception JRAF
 */
private List getProjectResultList(List pResultDTOs, List pCurrentAudits, List pChildren)
        throws JrafEnterpriseException {
    ListIterator auditIterator = pCurrentAudits.listIterator();
    AuditDTO currentAudit = null;
    // audit sur lequel on requiert des resultats
    ResultsDTO currentResults = null;
    // ResultsDTO pour les projets et les TREs
    List newResultDTOs = pResultDTOs;
    while (auditIterator.hasNext() && newResultDTOs != null) {

        // Initialisation de l'audit courant et chargement de resultats projets / TREs
        currentAudit = (AuditDTO) auditIterator.next();
        currentResults = getByFactorAndProject(currentAudit, pChildren);

        // Ajout a des resultats des projets / TREs a la collection de ResultsDTO pour un audit donn
        // L'indice dans la liste de ResultsDTO correspond a l'indice dans la liste d'audits
        /*
         * TODO tester que la premiere ligne de resultsDTO pour chaque projet est la meme SINON throw une exception
         */
        if (currentResults != null) {
            // Ajout des rsultats sur le RsultDTO de pResultDTOs correspondant au bon audit
            ResultsDTO resultDTO = ((ResultsDTO) newResultDTOs.get(auditIterator.nextIndex() - 1));
            resultDTO.getResultMap().putAll(currentResults.getResultMap());
        } else {
            newResultDTOs = null;
        }
    }
    return newResultDTOs;
}

From source file:zemin.notification.NotificationView.java

void onArrival(NotificationEntry entry) {
    synchronized (mEntryLock) {
        if (hasState(PAUSED)) {
            mNotificationHandler.onSendFinished(entry);
            return;
        }//ww w .ja  v  a2 s .  com

        ListIterator<NotificationEntry> iter = mEntries.listIterator();
        int index = mEntries.size();
        while (iter.hasNext()) {
            if (entry.priority.higher(iter.next().priority)) {
                index = iter.nextIndex() - 1;
                break;
            }
        }
        mEntries.add(index, entry);
        if (!hasState(TICKING)) {
            addState(TICKING);
            schedule(MSG_START);
        }
    }
}

From source file:org.clipsmonitor.core.MonitorGenMap.java

/**
 * Metodo per la verifica e la rimozione delle Move non piu valide a seguito
 * di un resize della mappa.Il metodo scorre la lista linkata e rimuove
 * tutte le move a partire dalla prima occorrenza non pu valida. Se ad un
 * certo step la move non  valida non lo saranno pi tutte quelle
 * successivamente create/*from  w ww. j  av a  2  s  .  co m*/
 */
public int[] RemoveStepAfterResize() {

    int[] pos = new int[2];
    ListIterator<Person> it = Persons.listIterator();
    while (it.hasNext()) {
        Person p = it.next();
        ListIterator<Path> itPath = p.paths.listIterator();
        while (itPath.hasNext()) {
            Path actual = itPath.next();
            ListIterator<StepMove> its = actual.move.listIterator();
            StepMove s = its.next();
            boolean flag = false;
            while (its.hasNext()) {
                if (s.getX() < 0 || s.getX() > NumCellX || s.getY() < 0 || s.getY() > NumCellY
                        || !PersonPositionIsValid(scene[s.getX()][s.getY()])) {
                    flag = true;
                    break;
                }
                s = its.next();
            }
            if (flag) {

                int end = its.nextIndex();

                for (int index = actual.move.size() - 1; index >= end - 1; index--) {
                    actual.move.remove(index);
                }

                if (itPath.hasNext()) {
                    ListIterator<Path> its2 = p.paths.listIterator(itPath.nextIndex());
                    while (its2.hasNext()) {
                        Path succ = its2.next();
                        succ.move.addFirst(actual.getMoves().getLast());
                        succ.move.getFirst().setStep(succ.startStep);
                        ListIterator<StepMove> its3 = succ.move.listIterator(1);
                        int steps = succ.startStep;
                        while (its3.hasNext()) {
                            its3.next().setStep(steps++);
                        }
                    }
                }
            }
        }

        if (p.paths.getFirst().move.isEmpty()) {
            RemoveLastPath(p.associatedColor);
            Remove(p.associatedColor);
        } else {
            StepMove s = p.paths.getLast().getMoves().getLast();
            pos[0] = s.x;
            pos[1] = s.y;
        }
    }

    return pos;
}

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

/**
 * Phase 3 of Knuth algorithm: Adds the areas
 * @param alg PageBreakingAlgorithm instance which determined the breaks
 * @param startPart index of the first part (page) to be rendered
 * @param partCount number of parts (pages) to be rendered
 * @param originalList original Knuth element list
 * @param effectiveList effective Knuth element list (after adjustments)
 *//*from ww  w .  ja  v  a  2s . c  o m*/
protected void addAreas(PageBreakingAlgorithm alg, int startPart, int partCount, BlockSequence originalList,
        BlockSequence effectiveList) {
    LayoutContext childLC;
    // add areas
    int startElementIndex = 0;
    int endElementIndex = 0;
    int lastBreak = -1;
    for (int p = startPart; p < startPart + partCount; p++) {
        PageBreakPosition pbp = alg.getPageBreaks().get(p);

        //Check the last break position for forced breaks
        int lastBreakClass;
        if (p == 0) {
            lastBreakClass = effectiveList.getStartOn();
        } else {
            ListElement lastBreakElement = effectiveList.getElement(endElementIndex);
            if (lastBreakElement.isPenalty()) {
                KnuthPenalty pen = (KnuthPenalty) lastBreakElement;
                lastBreakClass = pen.getBreakClass();
            } else {
                lastBreakClass = Constants.EN_COLUMN;
            }
        }

        //the end of the new part
        endElementIndex = pbp.getLeafPos();

        // ignore the first elements added by the
        // PageSequenceLayoutManager
        startElementIndex += (startElementIndex == 0) ? effectiveList.ignoreAtStart : 0;

        log.debug("PLM> part: " + (p + 1) + ", start at pos " + startElementIndex + ", break at pos "
                + endElementIndex + ", break class = " + getBreakClassName(lastBreakClass));

        startPart(effectiveList, lastBreakClass);

        int displayAlign = getCurrentDisplayAlign();

        //The following is needed by SpaceResolver.performConditionalsNotification()
        //further down as there may be important Position elements in the element list trailer
        int notificationEndElementIndex = endElementIndex;

        // ignore the last elements added by the
        // PageSequenceLayoutManager
        endElementIndex -= (endElementIndex == (originalList.size() - 1)) ? effectiveList.ignoreAtEnd : 0;

        // ignore the last element in the page if it is a KnuthGlue
        // object
        if (((KnuthElement) effectiveList.get(endElementIndex)).isGlue()) {
            endElementIndex--;
        }

        // ignore KnuthGlue and KnuthPenalty objects
        // at the beginning of the line
        ListIterator<KnuthElement> effectiveListIterator = effectiveList.listIterator(startElementIndex);
        while (effectiveListIterator.hasNext() && !(effectiveListIterator.next()).isBox()) {
            startElementIndex++;
        }

        if (startElementIndex <= endElementIndex) {
            if (log.isDebugEnabled()) {
                log.debug("     addAreas from " + startElementIndex + " to " + endElementIndex);
            }
            childLC = new LayoutContext(0);
            // set the space adjustment ratio
            childLC.setSpaceAdjust(pbp.bpdAdjust);
            // add space before if display-align is center or bottom
            // add space after if display-align is distribute and
            // this is not the last page
            if (pbp.difference != 0 && displayAlign == Constants.EN_CENTER) {
                childLC.setSpaceBefore(pbp.difference / 2);
            } else if (pbp.difference != 0 && displayAlign == Constants.EN_AFTER) {
                childLC.setSpaceBefore(pbp.difference);
            } else if (pbp.difference != 0 && displayAlign == Constants.EN_X_DISTRIBUTE
                    && p < (partCount - 1)) {
                // count the boxes whose width is not 0
                int boxCount = 0;
                effectiveListIterator = effectiveList.listIterator(startElementIndex);
                while (effectiveListIterator.nextIndex() <= endElementIndex) {
                    KnuthElement tempEl = effectiveListIterator.next();
                    if (tempEl.isBox() && tempEl.getWidth() > 0) {
                        boxCount++;
                    }
                }
                // split the difference
                if (boxCount >= 2) {
                    childLC.setSpaceAfter(pbp.difference / (boxCount - 1));
                }
            }

            /* *** *** non-standard extension *** *** */
            if (displayAlign == Constants.EN_X_FILL) {
                int averageLineLength = optimizeLineLength(effectiveList, startElementIndex, endElementIndex);
                if (averageLineLength != 0) {
                    childLC.setStackLimitBP(MinOptMax.getInstance(averageLineLength));
                }
            }
            /* *** *** non-standard extension *** *** */

            // Handle SpaceHandling(Break)Positions, see SpaceResolver!
            SpaceResolver.performConditionalsNotification(effectiveList, startElementIndex,
                    notificationEndElementIndex, lastBreak);

            // Add areas now!
            addAreas(new KnuthPossPosIter(effectiveList, startElementIndex, endElementIndex + 1), childLC);
        } else {
            //no content for this part
            handleEmptyContent();
        }

        finishPart(alg, pbp);

        lastBreak = endElementIndex;
        startElementIndex = pbp.getLeafPos() + 1;
    }
}