Example usage for java.util List listIterator

List of usage examples for java.util List listIterator

Introduction

In this page you can find the example usage for java.util List listIterator.

Prototype

ListIterator<E> listIterator();

Source Link

Document

Returns a list iterator over the elements in this list (in proper sequence).

Usage

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

private void fillArea(LayoutManager curLM) {

    int ipd = 1000000;

    LayoutContext childLC = new LayoutContext(LayoutContext.NEW_AREA);
    childLC.setLeadingSpace(new SpaceSpecifier(false));
    childLC.setTrailingSpace(new SpaceSpecifier(false));
    childLC.setRefIPD(ipd);//from  w  ww .ja va2 s  .  co  m

    int lineHeight = 14000;
    int lead = 12000;
    int follow = 2000;

    int halfLeading = (lineHeight - lead - follow) / 2;
    // height before baseline
    int lineLead = lead + halfLeading;
    // maximum size of top and bottom alignment
    int maxtb = follow + halfLeading;
    // max size of middle alignment below baseline
    int middlefollow = maxtb;

    stackSize = 0;

    List contentList = getNextKnuthElements(childLC, Constants.EN_START);
    ListIterator contentIter = contentList.listIterator();
    while (contentIter.hasNext()) {
        KnuthElement element = (KnuthElement) contentIter.next();
        if (element instanceof KnuthInlineBox) {
            KnuthInlineBox box = (KnuthInlineBox) element;
            // TODO handle alignment here?
        }
    }

    if (maxtb - lineLead > middlefollow) {
        middlefollow = maxtb - lineLead;
    }

    LayoutContext lc = new LayoutContext(0);

    lc.setFlags(LayoutContext.RESOLVE_LEADING_SPACE, true);
    lc.setLeadingSpace(new SpaceSpecifier(false));
    lc.setTrailingSpace(new SpaceSpecifier(false));
    KnuthPossPosIter contentPosIter = new KnuthPossPosIter(contentList, 0, contentList.size());
    curLM.addAreas(contentPosIter, lc);
}

From source file:es.tid.fiware.rss.expenditureLimit.server.service.ExpenditureLimitDataChecker.java

/**
 * //from   w w w  . j  a  v a  2s .  c o m
 * @param maxAmount
 * @param defaultProvThresholds
 */
private void checkNotificationLimits(Long maxAmount, List<Long> sNotifAmounts) throws RSSException {

    if ((maxAmount > 0) && (sNotifAmounts != null) && (sNotifAmounts.size() > 0)) {
        ListIterator<Long> litr = sNotifAmounts.listIterator();
        while (litr.hasNext()) {
            long notifAmount = litr.next().longValue();
            if (notifAmount > maxAmount) {
                String[] args = { "Amount notification (" + notifAmount + ") is greather than total limit ("
                        + maxAmount + ")" };
                throw new RSSException(UNICAExceptionType.INVALID_INPUT_VALUE, args);
            }
        }
    }
}

From source file:io.github.swagger2markup.markup.builder.internal.confluenceMarkup.ConfluenceMarkupBuilder.java

@Override
public MarkupDocBuilder tableWithColumnSpecs(List<MarkupTableColumn> columnSpecs, List<List<String>> cells) {
    Validate.notEmpty(cells, "cells must not be null");
    documentBuilder.append(newLine);// w w w. ja  va  2s.  c o  m
    if (columnSpecs != null && !columnSpecs.isEmpty()) {
        documentBuilder.append("||");
        for (MarkupTableColumn column : columnSpecs) {
            documentBuilder.append(formatCellContent(defaultString(column.header))).append("||");
        }
        documentBuilder.append(newLine);
    }
    for (List<String> row : cells) {
        documentBuilder.append(ConfluenceMarkup.TABLE_COLUMN_DELIMITER);
        ListIterator<String> cellIterator = row.listIterator();
        while (cellIterator.hasNext()) {
            int cellIndex = cellIterator.nextIndex();
            if (columnSpecs != null && columnSpecs.size() > cellIndex
                    && columnSpecs.get(cellIndex).headerColumn)
                documentBuilder.append(ConfluenceMarkup.TABLE_COLUMN_DELIMITER);

            documentBuilder.append(formatCellContent(cellIterator.next()))
                    .append(ConfluenceMarkup.TABLE_COLUMN_DELIMITER);
        }
        documentBuilder.append(newLine);
    }
    documentBuilder.append(newLine);
    return this;
}

From source file:nl.b3p.viewer.stripes.IbisEditFeatureActionBean.java

/**
 * Update any of the selected kavels to the given workflow.
 *
 * @param terreinID//from ww  w  . j  a  v a  2s  . c  o  m
 * @param kavelFilter
 * @param newStatus
 */
private void updateKavelWorkflowForTerrein(Filter kavelFilter, WorkflowStatus newStatus) {
    SimpleFeatureStore kavelStore = null;
    try (Transaction kavelTransaction = new DefaultTransaction("get-related-kavel-geom")) {
        EntityManager em = Stripersist.getEntityManager();
        log.debug("updating kavels voor terrein met filter: " + kavelFilter);
        // find kavel appLayer
        ApplicationLayer kavelAppLyr = null;
        List<ApplicationLayer> lyrs = this.getApplication().loadTreeCache(em).getApplicationLayers();
        for (ListIterator<ApplicationLayer> it = lyrs.listIterator(); it.hasNext();) {
            kavelAppLyr = it.next();
            if (kavelAppLyr.getLayerName().equalsIgnoreCase(KAVEL_LAYER_NAME)) {
                break;
            }
        }
        Layer l = kavelAppLyr.getService().getLayer(KAVEL_LAYER_NAME, em);
        kavelStore = (SimpleFeatureStore) l.getFeatureType().openGeoToolsFeatureSource();
        kavelStore.setTransaction(kavelTransaction);
        // update kavels
        kavelStore.modifyFeatures(WORKFLOW_FIELDNAME, newStatus, kavelFilter);
        kavelTransaction.commit();
        kavelTransaction.close();
    } catch (Exception e) {
        log.error(String.format("Bijwerken van kavel workflow status naar %s voor terrein met %s is mislukt.",
                newStatus, kavelFilter), e);
    } finally {
        if (kavelStore != null) {
            kavelStore.getDataStore().dispose();
        }
    }
}

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   www  .j  av  a 2 s .c  o  m
 * @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:de.csw.ontology.XWikiTextEnhancer.java

/**
 * Annotates the term by linking <code>term</code> to the search page of the
 * wiki.//w  w  w.ja  va2  s  .c  o  m
 * 
 * @param sb 
 *            the string builder the result is appended to
 * @param term
 *            a term
 * @param stemBase 
 *            the base form of the term
 */
protected void annotateWithSearch(StringBuilder sb, String term, String stemBase) {
    List<String> matches = index.getSimilarMatchLabels(term, MAX_SIMILAR_CONCEPTS);

    if (matches.isEmpty())
        return;

    sb.append("[[").append(term);
    sb.append(">>").append(getSearchURL(matches));
    sb.append("||class=\"similarconcept\"");
    Iterator<String> it = matches.listIterator();
    sb.append(" title=\"Suche nach den verwandten Begriffen: ");
    boolean afterFirstTerm = false;
    while (it.hasNext()) {
        String similarTerm = it.next();
        if (!stemBase.equals(this.index.getStemmer().stem(similarTerm))) {
            if (afterFirstTerm) {
                sb.append(", ");
            }
            sb.append(similarTerm);
            afterFirstTerm = true;
        }
    }
    sb.append("\"]]");
}

From source file:com.clearcenter.mobile_demo.mdStatusActivity.java

public void updateData() {
    JSONObject json_data;//from   w  w  w .ja v  a2 s . c  o  m

    String projection[] = new String[] { mdDeviceSamples.DATA };

    Cursor cursor = getContentResolver().query(mdDeviceSamples.CONTENT_URI, projection,
            mdDeviceSamples.NICKNAME + " = ?", new String[] { account_nickname }, null);

    int rows = 0;
    try {
        rows = cursor.getCount();
    } catch (NullPointerException e) {
    }

    Log.d(TAG, "Matches: " + rows);

    if (rows == 0) {
        Log.d(TAG, "No rows match for nickname: " + account_nickname);
        cursor.close();
        return;
    }

    cursor.moveToLast();

    String data = cursor.getString(cursor.getColumnIndex(mdDeviceSamples.DATA));

    try {
        json_data = new JSONObject(data);
        if (json_data.has("hostname"))
            hostname_textview.setText("Hostname: " + json_data.getString("hostname"));
        if (json_data.has("name") && json_data.has("release")) {
            final String release = json_data.getString("name") + " " + json_data.getString("release");
            release_textview.setText("Release: " + release);
        }
        if (json_data.has("time_locale")) {
            time_textview.setText("Clock: " + json_data.getString("time_locale"));
        }

        if (rows >= 2) {
            bw_graphview.reset();
            loadavg_graphview.reset();
            mem_graphview.reset();

            if (rows <= samples)
                cursor.moveToFirst();
            else
                cursor.move(-samples);

            long unix_time = 0;
            double bw_up = 0.0;
            double bw_down = 0.0;

            do {
                data = cursor.getString(cursor.getColumnIndex(mdDeviceSamples.DATA));

                final List<JSONObject> samples = sortedSamplesList(data);
                ListIterator<JSONObject> li = samples.listIterator();

                while (li.hasNext()) {
                    json_data = li.next();

                    if (unix_time == 0) {
                        bw_up = json_data.getDouble("bandwidth_up");
                        bw_down = json_data.getDouble("bandwidth_down");
                        unix_time = Long.valueOf(json_data.getString("time"));
                        continue;
                    }

                    long diff = Long.valueOf(json_data.getString("time")) - unix_time;

                    double rate_up = (json_data.getDouble("bandwidth_up") - bw_up) / diff;
                    double rate_down = (json_data.getDouble("bandwidth_down") - bw_down) / diff;

                    if (rate_up < 0.0)
                        rate_up = 0.0;
                    if (rate_down < 0.0)
                        rate_down = 0.0;

                    bw_graphview.addSample(bw_graph_up, unix_time, (float) rate_up);
                    bw_graphview.addSample(bw_graph_down, unix_time, (float) rate_down);

                    //                        Log.d(TAG, "time: " + diff +
                    //                            ", rate_up: " + rate_up + ", rate_down: " + rate_down);
                    bw_up = json_data.getDouble("bandwidth_up");
                    bw_down = json_data.getDouble("bandwidth_down");

                    loadavg_graphview.addSample(loadavg_graph_5min, unix_time,
                            (float) json_data.getDouble("loadavg_5min"));
                    loadavg_graphview.addSample(loadavg_graph_15min, unix_time,
                            (float) json_data.getDouble("loadavg_15min"));

                    mem_graphview.addSample(mem_graph_active, unix_time,
                            (float) json_data.getDouble("mem_active"));
                    mem_graphview.addSample(mem_graph_swap, unix_time,
                            (float) json_data.getDouble("mem_swap_used"));

                    unix_time = Long.valueOf(json_data.getString("time"));
                }
            } while (cursor.moveToNext());

            bw_graphview.update();
            loadavg_graphview.update();
            mem_graphview.update();
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSONException", e);
    }

    cursor.close();
}

From source file:es.tid.fiware.rss.service.SettlementManager.java

/**
 * Get files from path.//from   w w w.j  a v  a 2  s.  c  o  m
 * 
 * @param path
 * @return
 */
public List<RSSFile> getSettlementFilesOfPath(String path) {
    // Opening/creating the folder
    File folder = new File(path);
    List<RSSFile> rssFilesList = new ArrayList<RSSFile>();
    RSSFile rssf = new RSSFile();

    if (folder.exists() && folder.isDirectory()) {
        File[] files = folder.listFiles();
        Arrays.sort(files);

        if (files.length > 0) {
            List<File> fileList = new ArrayList<File>(Arrays.asList(files));
            ListIterator<File> lit = fileList.listIterator();

            while (lit.hasNext()) {
                File file = lit.next();
                logger.info(file.getAbsolutePath());

                if (file.isDirectory()) {
                    logger.debug("Is directory. Getting more files...");
                    File[] moreFiles = file.listFiles();
                    Arrays.sort(moreFiles);
                    if (moreFiles.length > 0) {
                        for (File f : moreFiles) {
                            lit.add(f);
                            lit.previous();
                        }
                    }
                } else {
                    rssf = new RSSFile();
                    rssf.setTxName(file.getName());
                    rssf.setTxUrl(file.getAbsolutePath());
                    rssFilesList.add(rssf);
                    logger.debug("File added");
                }
            }
        }
    }
    return rssFilesList;
}

From source file:com.appdynamics.demo.gasp.service.RestaurantSyncService.java

@Override
public void onCompleted(String results) {
    Log.i(TAG, "Response from " + mGaspRestaurantsUri.toString() + " :" + results + '\n');

    if (results != null) {
        try {//from w  w  w. java 2  s.c om
            Gson gson = new Gson();
            Type type = new TypeToken<List<Restaurant>>() {
            }.getType();
            List<Restaurant> restaurants = gson.fromJson(results, type);

            // Check how many records already in local SQLite database
            long localRecords = checkLastId();

            RestaurantDataAdapter restaurantsDB = new RestaurantDataAdapter(getApplicationContext());
            restaurantsDB.open();
            ListIterator<Restaurant> iterator = restaurants.listIterator();
            int index = 0;

            while (iterator.hasNext()) {
                try {
                    Restaurant restaurant = iterator.next();
                    if (restaurant.getId() > localRecords) {
                        restaurantsDB.insert(restaurant);
                        index = restaurant.getId();
                    }
                } catch (SQLiteConstraintException e) {
                    e.printStackTrace();
                }
            }
            restaurantsDB.close();

            String resultTxt = "Sync: Found " + localRecords + ", Loaded " + index + " restaurants from "
                    + mGaspRestaurantsUri;
            Log.i(TAG, resultTxt + '\n');

            // Notify LocationsActivity that Gasp restaurant data has been synced
            LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(LocationsActivity.SYNC_COMPLETED));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.rr.wabshs.ui.hierarchy.hierarchyController.java

/**
 * The 'getSecondTierList.do' GET request will return the list of tier 2 available to the user.
 * @param session/*from  www  . j a  v a  2  s .  com*/
 * @param surveyId
 * @return
 * @throws Exception 
 */
@RequestMapping(value = "getSecondTierList.do", method = RequestMethod.GET)
@ResponseBody
public ModelAndView getSecondTierList(HttpSession session,
        @RequestParam(value = "surveyId", required = false) Integer surveyId) throws Exception {

    ModelAndView mav = new ModelAndView();
    mav.setViewName("/survey/tier2Select");

    User userDetails = (User) session.getAttribute("userDetails");

    programOrgHierarchy topLevel = hierarchymanager.getProgramOrgHierarchyBydspPos(1, programId);

    /* Get a list of top level entities */
    Integer userId = 0;
    if (userDetails.getRoleId() == 3) {
        userId = userDetails.getId();
    }
    List<programHierarchyDetails> topLevelEntities = hierarchymanager.getProgramHierarchyItems(topLevel.getId(),
            userId);

    List<firstTierEntities> tier1EntityList = new ArrayList<firstTierEntities>();

    encryptObject encrypt = new encryptObject();
    Map<String, String> map;

    for (programHierarchyDetails topentity : topLevelEntities) {

        firstTierEntities newfirstTierEntity = new firstTierEntities();
        newfirstTierEntity.setId(topentity.getId());
        newfirstTierEntity.setName(topentity.getName());

        List secondLevelEntities = hierarchymanager.getProgramOrgHierarchyItems(programId, 2, topentity.getId(),
                userId);

        List<secondTierEntities> tier2EntityList = new ArrayList<secondTierEntities>();

        if (!secondLevelEntities.isEmpty() && secondLevelEntities.size() > 0) {

            for (ListIterator iter = secondLevelEntities.listIterator(); iter.hasNext();) {

                Object[] row = (Object[]) iter.next();

                secondTierEntities newSecondTierEntity = new secondTierEntities();
                newSecondTierEntity.setId(Integer.parseInt(row[0].toString()));
                newSecondTierEntity.setName(row[1].toString());
                newSecondTierEntity.setLastSurveyTaken("");
                newSecondTierEntity.setLastSurveyTakenOn(null);

                //Encrypt the use id to pass in the url
                map = new HashMap<String, String>();
                map.put("id", Integer.toString(Integer.parseInt(row[0].toString())));
                map.put("topSecret", topSecret);

                String[] encrypted = encrypt.encryptObject(map);

                newSecondTierEntity.setEncryptedId(encrypted[0]);
                newSecondTierEntity.setEncryptedSecret(encrypted[1]);

                tier2EntityList.add(newSecondTierEntity);

            }

            newfirstTierEntity.setTier2EntityList(tier2EntityList);
        }

        tier1EntityList.add(newfirstTierEntity);
    }

    mav.addObject("tier1EntityList", tier1EntityList);

    //Encrypt the use id to pass in the url
    mav.addObject("surveyId", surveyId);

    return mav;

}