Example usage for java.util ListIterator hasPrevious

List of usage examples for java.util ListIterator hasPrevious

Introduction

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

Prototype

boolean hasPrevious();

Source Link

Document

Returns true if this list iterator has more elements when traversing the list in the reverse direction.

Usage

From source file:uk.ac.ucl.excites.sapelli.storage.eximport.csv.CSVRecordsImporter.java

private void parseHeaderRow(String row) throws Exception {
    // Check row length:
    if (row.isEmpty())
        throw new IllegalArgumentException("Header row cannot be null");

    // Get separator by reading last char of the header:
    try {//from ww  w  .ja  v a  2 s .co  m
        separator = Separator.getSeparator(row.charAt(row.length() - 1));
    } catch (IllegalArgumentException iae) {
        separator = CSVRecordsExporter.DEFAULT_SEPARATOR;
        addWarning("Header row does no contain separator hint, trying to parse file using default separator ("
                + separator.toString() + ").");
    }

    // Split header row:
    List<String> headers = splitRow(row);

    // Parse attribute headers:
    Long modelID = null;
    Integer modelSchemaNo = null;
    String schemaName = null;
    try {
        ListIterator<String> headerIter = headers.listIterator(headers.size());
        String attributeHeader;
        int equalsPos;
        //   Iterate over headers back to front until we hit one without '=':
        while (headerIter.hasPrevious()
                && (equalsPos = (attributeHeader = headerIter.previous()).indexOf('=')) != -1) {
            switch (attributeHeader.substring(0, equalsPos)) {
            case Schema.ATTRIBUTE_MODEL_ID:
                modelID = Long.valueOf(attributeHeader.substring(equalsPos + 1));
                break;
            case Schema.ATTRIBUTE_MODEL_SCHEMA_NUMBER:
                modelSchemaNo = Integer.valueOf(attributeHeader.substring(equalsPos + 1));
                break;
            case Schema.ATTRIBUTE_SCHEMA_NAME:
                schemaName = deescapeAndUnquote(attributeHeader.substring(equalsPos + 1));
                break;
            case Exporter.ATTRIBUTE_EXPORTED_AT:
                try {
                    exportedAt = new TimeStamp(Exporter.ExportedAtFormatter.withOffsetParsed()
                            .parseDateTime(attributeHeader.substring(equalsPos + 1)));
                } catch (Exception e) {
                    addWarning(
                            "Error upon parsing exportedAt time: " + attributeHeader.substring(equalsPos + 1));
                }
                break;
            default:
                addWarning("Ignored unrecognised attribute header: " + attributeHeader);
            }
            // Remove attribute header:
            headerIter.remove();
        }
    } catch (Exception e) {
        // don't throw here
        client.logWarning("Error upon parsing CSV attribute header: " + ExceptionHelpers.getMessageAndCause(e));
    }

    // Get schema:
    if (modelID != null && modelSchemaNo != null) {
        Schema headerSchema = null;
        try {
            headerSchema = client.getSchema(modelID, modelSchemaNo, schemaName);
        } catch (Exception e) {
            if (schema != null)
                addWarning("Could not find schema: " + e.getMessage() + ". Using fallback schema ("
                        + schema.toString() + ").");
            else
                throw e;
        }
        if (schema != null && !headerSchema.equals(schema))
            addWarning("CSV schema (" + headerSchema.toString() + ") is different from given fallback schema ("
                    + schema.toString() + ").");
        schema = headerSchema; // !!!
    } else {
        String error = "No (readable) model/schema information in header!";
        if (schema != null)
            addWarning(error + " Using fallback schema (" + schema.toString() + ").");
        else
            throw new Exception("Could not find model/schema information in header!");
    }

    if (schema != null) {
        // Parse column headers:
        List<ColumnPointer<?>> headerColumnPointers = new ArrayList<ColumnPointer<?>>(headers.size());
        for (String columnHeader : headers) // (the remaining headers should all be qualified column names)
            headerColumnPointers.add(ColumnPointer.ByName(schema, columnHeader, false, false));
        // if we get her nothing went wrong above:
        this.columnPointers = headerColumnPointers;
    }
}

From source file:org.cloudata.core.common.conf.CloudataConf.java

private void loadResources(Properties props, ArrayList resources, boolean reverse, boolean quiet) {
    ListIterator i = resources.listIterator(reverse ? resources.size() : 0);
    while (reverse ? i.hasPrevious() : i.hasNext()) {
        loadResource(props, reverse ? i.previous() : i.next(), quiet);
    }//from w  w  w.  ja  va2  s. c o  m
}

From source file:mekhq.Utilities.java

public static Map<String, Integer> sortMapByValue(Map<String, Integer> unsortMap, boolean highFirst) {

    // Convert Map to List
    List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet());

    // Sort list with comparator, to compare the Map values
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        @Override/*from   ww  w  .j  ava 2  s. c  om*/
        public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });

    // Convert sorted map back to a Map
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    if (highFirst) {
        ListIterator<Map.Entry<String, Integer>> li = list.listIterator(list.size());
        while (li.hasPrevious()) {
            Map.Entry<String, Integer> entry = li.previous();
            sortedMap.put(entry.getKey(), entry.getValue());
        }
    } else {
        for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext();) {
            Map.Entry<String, Integer> entry = it.next();
            sortedMap.put(entry.getKey(), entry.getValue());
        }
    }

    return sortedMap;
}

From source file:chat.viska.commons.pipelines.Pipeline.java

private void processException(ListIterator<Map.Entry<String, Pipe>> iterator, Exception cause,
        boolean isReading) {
    while (isReading ? iterator.hasNext() : iterator.hasPrevious()) {
        final Pipe pipe = isReading ? iterator.next().getValue() : iterator.previous().getValue();
        try {/* ww w  .  j  a  v a  2  s.  com*/
            if (isReading) {
                pipe.catchInboundException(this, cause);
            } else {
                pipe.catchOutboundException(this, cause);
            }
            return;
        } catch (Exception rethrown) {
            cause = rethrown;
        }
    }
    triggerEvent(new ExceptionCaughtEvent(this, cause));
}

From source file:org.apache.atlas.model.typedef.AtlasStructDef.java

public void setAttributeDefs(List<AtlasAttributeDef> attributeDefs) {
    if (this.attributeDefs != null && this.attributeDefs == attributeDefs) {
        return;//from   w  ww . j a va  2  s.com
    }

    if (CollectionUtils.isEmpty(attributeDefs)) {
        this.attributeDefs = new ArrayList<>();
    } else {
        // if multiple attributes with same name are present, keep only the last entry
        List<AtlasAttributeDef> tmpList = new ArrayList<>(attributeDefs.size());
        Set<String> attribNames = new HashSet<>();

        ListIterator<AtlasAttributeDef> iter = attributeDefs.listIterator(attributeDefs.size());
        while (iter.hasPrevious()) {
            AtlasAttributeDef attributeDef = iter.previous();
            String attribName = attributeDef != null ? attributeDef.getName() : null;

            if (attribName != null) {
                attribName = attribName.toLowerCase();

                if (!attribNames.contains(attribName)) {
                    tmpList.add(new AtlasAttributeDef(attributeDef));

                    attribNames.add(attribName);
                }
            }
        }
        Collections.reverse(tmpList);

        this.attributeDefs = tmpList;
    }
}

From source file:org.apache.cayenne.access.DbGenerator.java

/**
 * Executes a set of commands to drop/create database objects. This is the
 * main worker method of DbGenerator. Command set is built based on
 * pre-configured generator settings.//from   www .  j  a v a 2s .co m
 */
public void runGenerator(DataSource ds) throws Exception {
    this.failures = null;

    try (Connection connection = ds.getConnection();) {

        // drop tables
        if (shouldDropTables) {
            ListIterator<DbEntity> it = dbEntitiesInInsertOrder.listIterator(dbEntitiesInInsertOrder.size());
            while (it.hasPrevious()) {
                DbEntity ent = it.previous();
                for (String statement : dropTables.get(ent.getName())) {
                    safeExecute(connection, statement);
                }
            }
        }

        // create tables
        List<String> createdTables = new ArrayList<>();
        if (shouldCreateTables) {
            for (final DbEntity ent : dbEntitiesInInsertOrder) {

                // only create missing tables

                safeExecute(connection, createTables.get(ent.getName()));
                createdTables.add(ent.getName());
            }
        }

        // create FK
        if (shouldCreateTables && shouldCreateFKConstraints) {
            for (DbEntity ent : dbEntitiesInInsertOrder) {

                if (createdTables.contains(ent.getName())) {
                    List<String> fks = createConstraints.get(ent.getName());
                    for (String fk : fks) {
                        safeExecute(connection, fk);
                    }
                }
            }
        }

        // drop PK
        if (shouldDropPKSupport) {
            List<String> dropAutoPKSQL = getAdapter().getPkGenerator()
                    .dropAutoPkStatements(dbEntitiesRequiringAutoPK);
            for (final String sql : dropAutoPKSQL) {
                safeExecute(connection, sql);
            }
        }

        // create pk
        if (shouldCreatePKSupport) {
            List<String> createAutoPKSQL = getAdapter().getPkGenerator()
                    .createAutoPkStatements(dbEntitiesRequiringAutoPK);
            for (final String sql : createAutoPKSQL) {
                safeExecute(connection, sql);
            }
        }

        new DbGeneratorPostprocessor().execute(connection, getAdapter());
    }
}

From source file:org.apache.cloudstack.api.response.QuotaResponseBuilderImpl.java

@Override
public QuotaBalanceResponse createQuotaBalanceResponse(List<QuotaBalanceVO> quotaBalance, Date startDate,
        Date endDate) {//w  ww .  j a  va  2 s.  c  o m
    if (quotaBalance == null || quotaBalance.isEmpty()) {
        throw new InvalidParameterValueException("The request period does not contain balance entries.");
    }
    Collections.sort(quotaBalance, new Comparator<QuotaBalanceVO>() {
        public int compare(QuotaBalanceVO o1, QuotaBalanceVO o2) {
            o1 = o1 == null ? new QuotaBalanceVO() : o1;
            o2 = o2 == null ? new QuotaBalanceVO() : o2;
            return o2.getUpdatedOn().compareTo(o1.getUpdatedOn()); // desc
        }
    });

    boolean have_balance_entries = false;
    //check that there is at least one balance entry
    for (Iterator<QuotaBalanceVO> it = quotaBalance.iterator(); it.hasNext();) {
        QuotaBalanceVO entry = it.next();
        if (entry.isBalanceEntry()) {
            have_balance_entries = true;
            break;
        }
    }
    //if last entry is a credit deposit then remove that as that is already
    //accounted for in the starting balance after that entry, note the sort is desc
    if (have_balance_entries) {
        ListIterator<QuotaBalanceVO> li = quotaBalance.listIterator(quotaBalance.size());
        // Iterate in reverse.
        while (li.hasPrevious()) {
            QuotaBalanceVO entry = li.previous();
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("createQuotaBalanceResponse: Entry=" + entry);
            }
            if (entry.getCreditsId() > 0) {
                li.remove();
            } else {
                break;
            }
        }
    }

    int quota_activity = quotaBalance.size();
    QuotaBalanceResponse resp = new QuotaBalanceResponse();
    BigDecimal lastCredits = new BigDecimal(0);
    boolean consecutive = true;
    for (Iterator<QuotaBalanceVO> it = quotaBalance.iterator(); it.hasNext();) {
        QuotaBalanceVO entry = it.next();
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("createQuotaBalanceResponse: All Credit Entry=" + entry);
        }
        if (entry.getCreditsId() > 0) {
            if (consecutive) {
                lastCredits = lastCredits.add(entry.getCreditBalance());
            }
            resp.addCredits(entry);
            it.remove();
        } else {
            consecutive = false;
        }
    }

    if (quota_activity > 0 && quotaBalance.size() > 0) {
        // order is desc last item is the start item
        QuotaBalanceVO startItem = quotaBalance.get(quotaBalance.size() - 1);
        QuotaBalanceVO endItem = quotaBalance.get(0);
        resp.setStartDate(startDate);
        resp.setStartQuota(startItem.getCreditBalance());
        resp.setEndDate(endDate);
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("createQuotaBalanceResponse: Start Entry=" + startItem);
            s_logger.debug("createQuotaBalanceResponse: End Entry=" + endItem);
        }
        resp.setEndQuota(endItem.getCreditBalance().add(lastCredits));
    } else if (quota_activity > 0) {
        // order is desc last item is the start item
        resp.setStartDate(startDate);
        resp.setStartQuota(new BigDecimal(0));
        resp.setEndDate(endDate);
        resp.setEndQuota(new BigDecimal(0).add(lastCredits));
    } else {
        resp.setStartDate(startDate);
        resp.setEndDate(endDate);
        resp.setStartQuota(new BigDecimal(0));
        resp.setEndQuota(new BigDecimal(0));
    }
    resp.setCurrency(QuotaConfig.QuotaCurrencySymbol.value());
    resp.setObjectName("balance");
    return resp;
}

From source file:com.edgenius.wiki.render.macro.BaseMacro.java

/**
 * Move Iterator cursor backward or forward to given node. You must ensure then direction is correct! 
 * This location will only following "forward inertia". <br>
 * "Inertia" means, if iterator goes previous, then next, the same cursor will return, likewise in next->previous.
 * (see {@link com.edgenius.wiki.gwt.client.html.TestHTMLNodeContainer#testIteratorAdd()}) <br>
 * /*from w ww .  j av  a2  s. com*/
 * This method will if call next(), it already return next HTMNode from current cursor. But if call previous(), 
 * it returns current cursor at first time. 
 *  
 * @param node
 * @param iter
 * @param forward
 */
protected void moveIteratorCursorTo(HTMLNode node, ListIterator<HTMLNode> iter, boolean forward) {
    if (forward) {
        if (iter.hasNext()) {
            HTMLNode cursor = iter.next();
            if (cursor.previous() != node) { //this is just ensure, iter current position is not equals with given node 
                while (cursor != node && iter.hasNext()) {
                    cursor = iter.next();
                }
            }
        }
    } else {
        //backward
        if (iter.hasPrevious()) {
            HTMLNode cursor = iter.previous();
            if (cursor.next() != node) { //this is just ensure, iter current position is not equals with given node 
                while (cursor != node && iter.hasPrevious()) {
                    cursor = iter.previous();
                }
            }
            //delete inertia
            iter.next();
        }
    }
}

From source file:arun.com.chromer.webheads.WebHeadService.java

private void selectNextMaster() {
    final ListIterator<String> it = new ArrayList<>(webHeads.keySet()).listIterator(webHeads.size());
    //noinspection LoopStatementThatDoesntLoop
    while (it.hasPrevious()) {
        final String key = it.previous();
        final WebHead toBeMaster = webHeads.get(key);
        if (toBeMaster != null) {
            toBeMaster.setMaster(true);// w w  w.  j a v  a  2  s . c o m
            updateSpringChain();
            toBeMaster.goToMasterTouchDownPoint();
        }
        break;
    }
}

From source file:com.quigley.filesystem.FilesystemPath.java

public FilesystemPath simplify() {
    List<String> elementsCopy = new ArrayList<String>(elements);
    ListIterator<String> i = elementsCopy.listIterator();
    boolean saw = false;
    while (i.hasNext()) {
        String value = i.next();//from   ww  w  . ja  v a 2 s.co  m
        if (value.equals(".")) {
            i.remove();
        } else if (value.equals("..")) {
            if (saw) {
                if (i.hasPrevious()) {
                    i.remove();
                    i.previous();
                    i.remove();
                }
            }
        } else {
            saw = true;
        }
    }
    FilesystemPath pathCopy = new FilesystemPath(elementsCopy);
    pathCopy.isAbsolute = isAbsolute;

    return pathCopy;
}