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:hudson.maven.reporters.SurefireArchiver.java

/**
 * Up to 1.372, there was a bug that causes Hudson to persist {@link SurefireArchiver} with the entire test result
 * in it. If we are loading those, fix it up in memory to reduce the memory footprint.
 *
 * It'd be nice we can save the record to remove problematic portion, but that might have
 * additional side effect.//  ww  w  .ja v  a 2s. c  o m
 */
public static void fixUp(List<MavenProjectActionBuilder> builders) {
    if (builders == null)
        return;
    for (ListIterator<MavenProjectActionBuilder> itr = builders.listIterator(); itr.hasNext();) {
        MavenProjectActionBuilder b = itr.next();
        if (b instanceof SurefireArchiver)
            itr.set(new FactoryImpl());
    }
}

From source file:nl.b3p.viewer.ibis.util.WorkflowUtil.java

/**
 * Update the geometry of the TERREIN. Must be called after the kavels
 * transaction. voor definitief terrein definitief kavels gebruiken, voor
 * bewerkt terrein definitef en bewerkt kavel genbruiken
 *
 * @param terreinID// w  w  w  .ja v a2s .c o  m
 * @param layer kavels layer
 * @param kavelStatus
 * @param application
 * @param em
 */
public static void updateTerreinGeometry(Integer terreinID, Layer layer, WorkflowStatus kavelStatus,
        Application application, EntityManager em) {
    log.debug("Updating terrein geometry for " + terreinID);
    SimpleFeatureStore terreinStore = null;
    SimpleFeatureStore kavelStore = null;
    FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
    Transaction terreinTransaction = new DefaultTransaction("edit-terrein-geom");
    Transaction kavelTransaction = new DefaultTransaction("get-kavel-geom");
    try {
        // determine whichs kavels to use for calcutating new geometry
        Filter kavelFilter = Filter.EXCLUDE;
        switch (kavelStatus) {
        case bewerkt:
            // find all "definitief" and "bewerkt" kavel for terreinID
            kavelFilter = ff.and(ff.equals(ff.property(KAVEL_TERREIN_ID_FIELDNAME), ff.literal(terreinID)),
                    ff.or(ff.equal(ff.property(WORKFLOW_FIELDNAME),
                            ff.literal(WorkflowStatus.bewerkt.toString()), false),
                            ff.equal(ff.property(WORKFLOW_FIELDNAME),
                                    ff.literal(WorkflowStatus.definitief.toString()), false)));
            break;
        case archief:
        case afgevoerd:
        case definitief:
            // find all "definitief" kavel for terreinID
            kavelFilter = ff.and(ff.equals(ff.property(KAVEL_TERREIN_ID_FIELDNAME), ff.literal(terreinID)),
                    ff.equal(ff.property(WORKFLOW_FIELDNAME), ff.literal(WorkflowStatus.definitief.toString()),
                            false));
            break;
        default:
            // do nothing / should not happen
        }
        log.debug("Looking for kavel with filter: " + kavelFilter);

        kavelStore = (SimpleFeatureStore) layer.getFeatureType().openGeoToolsFeatureSource();
        kavelStore.setTransaction(kavelTransaction);
        SimpleFeatureCollection kavels = kavelStore.getFeatures(kavelFilter);

        // dissolve all kavel geometries
        final Collection<Geometry> kavelGeoms = new ArrayList();
        kavels.accepts(new AbstractFeatureVisitor() {
            @Override
            public void visit(Feature feature) {
                Geometry geom = (Geometry) feature.getDefaultGeometryProperty().getValue();
                if (geom != null) {
                    kavelGeoms.add(geom);
                }
            }
        }, null);
        log.debug("Kavels found: " + kavelGeoms.size());
        GeometryFactory factory = JTSFactoryFinder.getGeometryFactory(null);
        GeometryCollection geometryCollection = (GeometryCollection) factory.buildGeometry(kavelGeoms);
        Geometry newTerreinGeom = geometryCollection.union();
        if (!newTerreinGeom.getGeometryType().equalsIgnoreCase("MultiPolygon")) {
            GeometryFactory f = JTSFactoryFinder.getGeometryFactory();
            newTerreinGeom = f.createMultiPolygon(new Polygon[] { (Polygon) newTerreinGeom });
        }

        // find terrein appLayer
        ApplicationLayer terreinAppLyr = null;
        List<ApplicationLayer> lyrs = application.loadTreeCache(em).getApplicationLayers();
        for (ListIterator<ApplicationLayer> it = lyrs.listIterator(); it.hasNext();) {
            terreinAppLyr = it.next();
            if (terreinAppLyr.getLayerName().equalsIgnoreCase(TERREIN_LAYER_NAME)) {
                break;
            }
        }
        Layer l = terreinAppLyr.getService().getLayer(TERREIN_LAYER_NAME, em);
        terreinStore = (SimpleFeatureStore) l.getFeatureType().openGeoToolsFeatureSource();
        terreinStore.setTransaction(terreinTransaction);

        // determine which terrein to update
        Filter terreinFilter = Filter.EXCLUDE;
        switch (kavelStatus) {
        case bewerkt:
            terreinFilter = ff.and(ff.equals(ff.property(ID_FIELDNAME), ff.literal(terreinID)), ff
                    .equal(ff.property(WORKFLOW_FIELDNAME), ff.literal(WorkflowStatus.bewerkt.name()), false));
            break;
        case archief:
        case afgevoerd:
        case definitief:
            terreinFilter = ff.and(ff.equals(ff.property(ID_FIELDNAME), ff.literal(terreinID)), ff.equal(
                    ff.property(WORKFLOW_FIELDNAME), ff.literal(WorkflowStatus.definitief.name()), false));
            break;
        default:
            // won't do anything
        }
        log.debug("Update terrein geom for kavels filtered by: " + terreinFilter);

        // update terrein with new geom
        String geomAttrName = terreinStore.getSchema().getGeometryDescriptor().getLocalName();
        terreinStore.modifyFeatures(geomAttrName, newTerreinGeom, terreinFilter);
        terreinTransaction.commit();
    } catch (Exception e) {
        log.error(String.format("Update van terrein geometrie %s is mislukt", terreinID), e);
    } finally {
        try {
            kavelTransaction.close();
            terreinTransaction.close();
        } catch (IOException io) {
            // closing transaction failed
        }
        if (terreinStore != null) {
            terreinStore.getDataStore().dispose();
        }
        if (kavelStore != null) {
            kavelStore.getDataStore().dispose();
        }
    }
}

From source file:Main.java

/**
 * Introduces overlap into a series of lists. 
 * @param before # of elements from the end of the previous list to prepend
 * @param after # of elements from the beginning of the next list to append
 *///from   w  w  w  .  j  ava 2  s .  com
public static <T> List<List<T>> overlap(List<List<T>> lists, int before, int after) {

    if (before < 0) {
        throw new IllegalArgumentException("Value of before cannot be negative");
    }
    if (after < 0) {
        throw new IllegalArgumentException("Value of after cannot be negative");
    }

    ListIterator<List<T>> iter = lists.listIterator();

    List<List<T>> result = new ArrayList<List<T>>();
    for (; iter.hasNext();) {
        List<T> current = new ArrayList<T>(iter.next());
        List<T> prev = before > 0 ? findPrevious(iter) : null;
        List<T> next = after > 0 ? findNext(iter) : null;
        if (prev != null) {
            List<T> overlap = prev.subList(prev.size() - before, prev.size());
            current.addAll(0, overlap);
        }
        if (next != null) {
            List<T> overlap = next.subList(0, after);
            current.addAll(overlap);
        }
        result.add(current);
    }

    return result;
}

From source file:com.wso2telco.core.mnc.resolver.dnsssl.DNSSSLQueryClient.java

/**
 * Perform single query.// w ww .  ja  v a  2 s  . c  o  m
 *
 * @param countryCode the country code
 * @param tn the tn
 * @param config the config
 * @param sslResolver the ssl resolver
 * @return the string
 */
private static String performSingleQuery(final String countryCode, final String tn,
        final MCCConfiguration config, final SSLResolver sslResolver) {

    String TN = "";
    try {

        DNSSSLQuery dnsSSLQuery = new DNSSSLQuery();

        DNSQueryResult queryResult = dnsSSLQuery.execute(countryCode, tn, config, sslResolver);

        List<String> naptrArray = new ArrayList<String>();

        Iterator<String> naptIt = naptrArray.listIterator();

        if ((queryResult != null) && (queryResult.getRcode() == RCODE.REFUSED)) {
            System.err.println(
                    "Got refused response from server.\n " + "Please contact NeuStar customer support, "
                            + "with the IP address and X.509 cert of the client machine");
        } else if (queryResult.getRcode() == RCODE.NXDOMAIN) {
            System.err.println("TN not found.\n" + " Please verify with NeuStar customer support that "
                    + "the terminating domain setting above matches the profile configuration");
        } else if (queryResult.getRcode() == RCODE.FORMAT_ERROR) {
            System.err.println("The query format appears to be incorrect,\n"
                    + " please verify whether you are using correct ENUM format for queries");

        } else if (queryResult.getRcode() == RCODE.SERVFAIL) {
            System.err.println("There was an internal server error which caused a failure to respond\n"
                    + " Please report to NeuStar customer support.");

        } else if (queryResult.getRcode() == RCODE.SERVER_NOT_FOUND) {
            System.err.println("Server could not be found, please check host name and port.");
        } else if (queryResult.getRcode() == RCODE.NO_ERROR) {
            System.out.println("TN match success. Route = ");
            naptrArray = queryResult.getNaptrArray();
            naptIt = naptrArray.listIterator();
            while (naptIt.hasNext()) {
                String naptrResult = naptIt.next();
                TN += " | " + naptrResult;
            }
        } else {
            System.err.println("Unanticipated error: " + queryResult.getRcode()
                    + ". Please contact NeuStar customer support");
        }

        // perform the clean up
        sslResolver.cleanUp();

    } catch (Exception e) {
        System.err.println("Exception occured while sending single query");
        e.printStackTrace();
    }
    return TN;
}

From source file:Main.java

public static <T> void symmetricSort(List<T> list) {
    @SuppressWarnings("unchecked")
    T[] array = (T[]) new Object[list.size()];
    for (int i = 0; i < list.size(); i++) {
        if (i % 2 == 0) {
            array[(list.size() - i) / 2 + (list.size() % 2 - 1)] = list.get(i);
        } else {/*from w  w  w .j  a v  a2s  .c  o m*/
            array[(list.size() + i) / 2] = list.get(i);
        }
    }

    int j = 0;
    ListIterator<T> it = list.listIterator();
    while (it.hasNext()) {
        it.next();
        it.set(array[j++]);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.utils.fields.FieldUtils.java

public static List<Individual> removeIndividualsAlreadyInRange(List<Individual> individuals,
        List<ObjectPropertyStatement> stmts, String predicateUri, String objectUriBeingEdited) {
    HashSet<String> range = new HashSet<String>();

    for (ObjectPropertyStatement ops : stmts) {
        if (ops.getPropertyURI().equals(predicateUri))
            range.add(ops.getObjectURI());
    }//from   w w w.  j  ava 2  s .c om

    int removeCount = 0;
    ListIterator<Individual> it = individuals.listIterator();
    while (it.hasNext()) {
        Individual ind = it.next();
        if (range.contains(ind.getURI()) && !(ind.getURI().equals(objectUriBeingEdited))) {
            it.remove();
            ++removeCount;
        }
    }

    return individuals;
}

From source file:com.aliyun.openservices.odps.console.resource.CreateResourceCommand.java

public static AddResourceCommand parse(String commandString, ExecutionContext sessionContext)
        throws ODPSConsoleException {

    String[] tokens = new AntlrObject(commandString).getTokenStringArray();

    if (tokens != null && tokens.length >= 2 && tokens[0].toUpperCase().equals("CREATE")
            && tokens[1].toUpperCase().equals("RESOURCE")) {

        GnuParser parser = new GnuParser();
        Options options = new Options();
        options.addOption("p", "project", true, null);
        options.addOption("c", "comment", true, null);
        options.addOption("f", "force", false, null);

        try {//from ww w.  ja  v  a  2  s. co m
            CommandLine cl = parser.parse(options, tokens);

            String refName = null;
            String alias = "";
            String comment = null;
            String type = null;
            String partitionSpec = "";
            boolean isUpdate = false;

            List<String> argList = cl.getArgList();
            int size = argList.size();

            if (size < 4) {
                throw new ODPSConsoleException(ODPSConsoleConstants.BAD_COMMAND + "Missing parameters");
            }

            ListIterator<String> iter = argList.listIterator();
            iter.next();
            iter.next();
            type = iter.next();
            refName = iter.next();
            if (iter.hasNext()) {
                String item = iter.next();
                if (item.equals("(")) {
                    boolean isParenPaired = false;

                    while (iter.hasNext()) {
                        String s = iter.next();
                        if (s.equals(")")) {
                            isParenPaired = true;
                            break;
                        }
                        partitionSpec += s;
                    }

                    if (!isParenPaired) {
                        throw new ODPSConsoleException(
                                ODPSConsoleConstants.BAD_COMMAND + "Unpaired parenthesis");
                    }

                    if (!iter.hasNext()) {
                        throw new ODPSConsoleException(
                                ODPSConsoleConstants.BAD_COMMAND + "Missing parameter: alias");
                    }
                    item = iter.next();
                }

                alias = item;
            }

            if (iter.hasNext()) {
                throw new ODPSConsoleException(
                        ODPSConsoleConstants.BAD_COMMAND + "Illegal parameter: " + iter.next());
            }

            String projectName = null;
            Option[] opts = cl.getOptions();
            for (Option opt : opts) {
                if ("f".equals(opt.getOpt())) {
                    isUpdate = true;
                } else if ("c".equals(opt.getOpt())) {
                    comment = opt.getValue();
                } else if ("p".equals(opt.getOpt())) {
                    projectName = opt.getValue();
                } else {
                    throw new ODPSConsoleException(
                            ODPSConsoleConstants.BAD_COMMAND + "Illegal option: " + opt.getOpt());
                }
            }

            return new AddResourceCommand(commandString, sessionContext, refName, alias, comment, type,
                    partitionSpec, isUpdate, projectName);
        } catch (ParseException e) {
            throw new ODPSConsoleException(ODPSConsoleConstants.BAD_COMMAND + "Invalid parameters");
        }
    } else {
        return null;
    }
}

From source file:org.jfree.data.statistics.BoxAndWhiskerCalculator.java

/**
 * Calculates the statistics required for a {@link BoxAndWhiskerItem}
 * from a list of <code>Number</code> objects.  Any items in the list
 * that are <code>null</code>, not an instance of <code>Number</code>, or
 * equivalent to <code>Double.NaN</code>, will be ignored.
 *
 * @param values  a list of numbers (a <code>null</code> list is not
 *                permitted).//from w  w w.  j  a  va2s.c  o m
 * @param stripNullAndNaNItems  a flag that controls the handling of null
 *     and NaN items.
 *
 * @return A box-and-whisker item.
 *
 * @since 1.0.3
 */
public static BoxAndWhiskerItem calculateBoxAndWhiskerStatistics(List values, boolean stripNullAndNaNItems) {

    ParamChecks.nullNotPermitted(values, "values");

    List vlist;
    if (stripNullAndNaNItems) {
        vlist = new ArrayList(values.size());
        Iterator iterator = values.listIterator();
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            if (obj instanceof Number) {
                Number n = (Number) obj;
                double v = n.doubleValue();
                if (!Double.isNaN(v)) {
                    vlist.add(n);
                }
            }
        }
    } else {
        vlist = values;
    }
    Collections.sort(vlist);

    double mean = Statistics.calculateMean(vlist, false);
    double median = Statistics.calculateMedian(vlist, false);
    double q1 = calculateQ1(vlist);
    double q3 = calculateQ3(vlist);

    double interQuartileRange = q3 - q1;

    double upperOutlierThreshold = q3 + (interQuartileRange * 1.5);
    double lowerOutlierThreshold = q1 - (interQuartileRange * 1.5);

    double upperFaroutThreshold = q3 + (interQuartileRange * 2.0);
    double lowerFaroutThreshold = q1 - (interQuartileRange * 2.0);

    double minRegularValue = Double.POSITIVE_INFINITY;
    double maxRegularValue = Double.NEGATIVE_INFINITY;
    double minOutlier = Double.POSITIVE_INFINITY;
    double maxOutlier = Double.NEGATIVE_INFINITY;
    List outliers = new ArrayList();

    Iterator iterator = vlist.iterator();
    while (iterator.hasNext()) {
        Number number = (Number) iterator.next();
        double value = number.doubleValue();
        if (value > upperOutlierThreshold) {
            outliers.add(number);
            if (value > maxOutlier && value <= upperFaroutThreshold) {
                maxOutlier = value;
            }
        } else if (value < lowerOutlierThreshold) {
            outliers.add(number);
            if (value < minOutlier && value >= lowerFaroutThreshold) {
                minOutlier = value;
            }
        } else {
            minRegularValue = Math.min(minRegularValue, value);
            maxRegularValue = Math.max(maxRegularValue, value);
        }
        minOutlier = Math.min(minOutlier, minRegularValue);
        maxOutlier = Math.max(maxOutlier, maxRegularValue);
    }

    return new BoxAndWhiskerItem(new Double(mean), new Double(median), new Double(q1), new Double(q3),
            new Double(minRegularValue), new Double(maxRegularValue), new Double(minOutlier),
            new Double(maxOutlier), outliers);

}

From source file:com.cloud.utils.UriUtils.java

public static String getUpdateUri(String url, boolean encrypt) {
    String updatedPath = null;//ww w .  j  ava  2  s .  c  o m
    try {
        String query = URIUtil.getQuery(url);
        URIBuilder builder = new URIBuilder(url);
        builder.removeQuery();

        StringBuilder updatedQuery = new StringBuilder();
        List<NameValuePair> queryParams = getUserDetails(query);
        ListIterator<NameValuePair> iterator = queryParams.listIterator();
        while (iterator.hasNext()) {
            NameValuePair param = iterator.next();
            String value = null;
            if ("password".equalsIgnoreCase(param.getName()) && param.getValue() != null) {
                value = encrypt ? DBEncryptionUtil.encrypt(param.getValue())
                        : DBEncryptionUtil.decrypt(param.getValue());
            } else {
                value = param.getValue();
            }

            if (updatedQuery.length() == 0) {
                updatedQuery.append(param.getName()).append('=').append(value);
            } else {
                updatedQuery.append('&').append(param.getName()).append('=').append(value);
            }
        }

        String schemeAndHost = "";
        URI newUri = builder.build();
        if (newUri.getScheme() != null) {
            schemeAndHost = newUri.getScheme() + "://" + newUri.getHost();
        }

        updatedPath = schemeAndHost + newUri.getPath() + "?" + updatedQuery;
    } catch (URISyntaxException e) {
        throw new CloudRuntimeException("Couldn't generate an updated uri. " + e.getMessage());
    }

    return updatedPath;
}

From source file:Main.java

private static <E> void updateList(List<E> origList, Collection<? extends E> updateList, boolean add,
        boolean replace, boolean remove, BiPredicate<? super E, ? super E> equalTester,
        BiConsumer<List<E>, Collection<? extends E>> adder) {
    List<E> itemsToRemove = null;
    List<E> itemsToAdd = null;
    for (E update : updateList) {
        boolean origListContainsUpdate = false;
        ListIterator<E> origIter = origList.listIterator();
        while (origIter.hasNext()) {
            E orig = origIter.next();/*from w  w  w  . jav  a  2 s . c  om*/
            if (equalTester.test(orig, update)) {
                origListContainsUpdate = true;
                if (remove) {
                    if (itemsToRemove == null) {
                        itemsToRemove = new ArrayList<>(origList);
                    }
                    itemsToRemove.remove(orig);
                }
                if (replace) {
                    origIter.set(update);
                }
                break;
            }
        }
        if (!origListContainsUpdate && add) {
            if (itemsToAdd == null) {
                itemsToAdd = new ArrayList<>();
            }
            itemsToAdd.add(update);
        }
    }
    if (remove) {
        if (itemsToRemove != null) {
            origList.removeAll(itemsToRemove);
        } else {
            origList.clear();
        }
    }
    if (itemsToAdd != null) {
        adder.accept(origList, itemsToAdd);
    }
}