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.slc.sli.dashboard.unit.client.SDKAPIClientTest.java

@Test
public void testGetAssessmentsForStudent()
        throws URISyntaxException, IOException, MessageProcessingException, SLIClientException {
    String token = "token";
    String key = "studentId";
    String studentId = "288598192";

    String filename = getFilename(MOCK_DATA_DIRECTORY + "common/" + MOCK_ASSESSMENTS_FILE);
    when(mockSdk.read(anyString())).thenReturn(fromFileWithValue(filename, studentId, key));

    List<GenericEntity> assessments = client.getAssessmentsForStudent(token, studentId);

    assertNotNull(assessments);//from ww w. ja va  2 s.  c  o m
    assertEquals(18, assessments.size());
    ListIterator<GenericEntity> li = assessments.listIterator();
    int count = 0;
    while (li.hasNext()) {
        GenericEntity ge = li.next();
        assertEquals(ge.getString(key), studentId);
        if (ge.getString("assessmentName").equals("StateTest_READING")) {
            count++;
        }
    }
    assertEquals(count, 6);
}

From source file:de.meisterfuu.animexxenger.ui.ContactList.java

/**
 * Get a {@link ContactListAdapter} for a group.
 * The {@link ContactListAdapter} will be created if it is not exist.
 * @param group the group/*from  www  .j a va2 s. c om*/
 * @return the adapter
 */
ContactListAdapter getContactListAdapter(String group) {
    synchronized (contactListAdapters) {
        ContactListAdapter contactListAdapter = contactListAdapters.get(group);
        if (contactListAdapter == null) {
            contactListAdapter = new ContactListAdapter(ContactList.this);
            contactListAdapters.put(group, contactListAdapter);
            List<GroupHolder> realGroups = mListGroup.subList(1, mListGroup.size() - 1);
            if (!GroupHolder.contains(mListGroup, group)) {
                GroupHolder gh = new GroupHolder(group);
                boolean added = false;
                // insert group in sorted list
                for (ListIterator<GroupHolder> iterator = realGroups.listIterator(); iterator.hasNext();) {
                    GroupHolder currentGroup = (GroupHolder) iterator.next();
                    if (currentGroup.group.compareTo(group) > 0) {
                        iterator.previous();
                        iterator.add(gh);
                        added = true;
                        break;
                    }
                }
                if (!added)
                    realGroups.add(gh);
                groupsPagesAdapter.notifyDataSetChanged();
                mAdapterBanner.notifyDataSetChanged();
            }
        }
        boolean hideDisconnected = mSettings.getBoolean(BeemApplication.SHOW_OFFLINE_CONTACTS_KEY, false);
        contactListAdapter.setOnlineOnly(hideDisconnected);
        return contactListAdapter;
    }
}

From source file:com.projity.pm.graphic.model.transform.NodeCacheTransformer.java

private void groupList(List list, List destList, ListIterator groupIterator, Node parentGroup,
        NodeTransformer composition, boolean preserveHierarchy) {
    NodeGroup group = (NodeGroup) groupIterator.next();
    NodeSorter sorter = group.getSorter();
    GraphicNodeComparator gcomp = new GraphicNodeComparator(sorter, composition);
    sorter.sortList(list, gcomp, preserveHierarchy);
    GraphicNode last = null;//from  www .  j  ava2s  .  co  m
    List nodes = null;
    GraphicNode current;
    for (ListIterator i = list.listIterator(); i.hasNext();) {
        current = (GraphicNode) i.next();
        if (last == null) {
            nodes = new LinkedList();
        } else if (gcomp.compare(last, current) != 0) {
            handleGroup(destList, groupIterator, parentGroup, group, last, nodes, composition,
                    preserveHierarchy);
            nodes = new LinkedList();
        }
        nodes.add(current);
        last = current;
    }
    if (nodes != null && nodes.size() > 0) {
        handleGroup(destList, groupIterator, parentGroup, group, last, nodes, composition, preserveHierarchy);
    }
    groupIterator.previous();
}

From source file:annis.visualizers.component.grid.EventExtractor.java

/**
* Returns the annotations to display according to the mappings configuration.
*
* This will check the "annos" and "annos_regex" paramters for determining.
* the annotations to display. It also iterates over all nodes of the graph
* matching the type.//w  ww .j  a v  a2s .  c  o  m
*
* @param input The input for the visualizer.
* @param type Which type of nodes to include
* @return
*/
public static List<String> computeDisplayAnnotations(VisualizerInput input, Class<? extends SNode> type) {
    if (input == null) {
        return new LinkedList<String>();
    }

    SDocumentGraph graph = input.getDocument().getSDocumentGraph();

    Set<String> annoPool = getAnnotationLevelSet(graph, input.getNamespace(), type);
    List<String> annos = new LinkedList<String>(annoPool);

    String annosConfiguration = input.getMappings().getProperty(MAPPING_ANNOS_KEY);
    if (annosConfiguration != null && annosConfiguration.trim().length() > 0) {
        String[] split = annosConfiguration.split(",");
        annos.clear();
        for (String s : split) {
            s = s.trim();
            // is regular expression?
            if (s.startsWith("/") && s.endsWith("/")) {
                // go over all remaining items in our pool of all annotations and
                // check if they match
                Pattern regex = Pattern.compile(StringUtils.strip(s, "/"));

                LinkedList<String> matchingAnnos = new LinkedList<String>();
                for (String a : annoPool) {
                    if (regex.matcher(a).matches()) {
                        matchingAnnos.add(a);
                    }
                }

                annos.addAll(matchingAnnos);
                annoPool.removeAll(matchingAnnos);

            } else {
                annos.add(s);
                annoPool.remove(s);
            }
        }
    }

    // filter already found annotation names by regular expression
    // if this was given as mapping
    String regexFilterRaw = input.getMappings().getProperty(MAPPING_ANNO_REGEX_KEY);
    if (regexFilterRaw != null) {
        try {
            Pattern regexFilter = Pattern.compile(regexFilterRaw);
            ListIterator<String> itAnnos = annos.listIterator();
            while (itAnnos.hasNext()) {
                String a = itAnnos.next();
                // remove entry if not matching
                if (!regexFilter.matcher(a).matches()) {
                    itAnnos.remove();
                }
            }
        } catch (PatternSyntaxException ex) {
            log.warn("invalid regular expression in mapping for grid visualizer", ex);
        }
    }
    return annos;
}

From source file:org.slc.sli.dashboard.unit.client.SDKAPIClientTest.java

@Test
public void testGetSchools()
        throws URISyntaxException, IOException, MessageProcessingException, SLIClientException {
    SDKAPIClient client = new SDKAPIClient() {
        @Override// w  w w.  ja  v  a 2 s  .  co m
        public String getId(String token) {
            return null;
        }

        @Override
        public List<GenericEntity> getSectionsForTeacher(String teacherId, String token,
                Map<String, String> params) {
            return null;
        }

        @Override
        public List<GenericEntity> getSectionsForNonEducator(String token, Map<String, String> params) {
            return null;
        }
    };
    SLIClientFactory factory = mock(SLIClientFactory.class);
    when(factory.getClientWithSessionToken(anyString())).thenReturn(mockSdk);
    client.setClientFactory(factory);

    SecurityContextHolder.getContext().setAuthentication(new Authentication() {
        @Override
        public String getName() {
            return null;
        }

        @Override
        public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        }

        @Override
        public boolean isAuthenticated() {
            return false;
        }

        @Override
        public Object getPrincipal() {
            return null;
        }

        @Override
        public Object getDetails() {
            return null;
        }

        @Override
        public Object getCredentials() {
            return null;
        }

        @Override
        public Collection<GrantedAuthority> getAuthorities() {
            return Collections.emptyList();
        }
    });

    String token = "token";
    String key = "schoolId";
    String[] idArr = { "Illinois PS145", "Illinois PS200" };
    List<String> schoolIds = Arrays.asList(idArr);

    String filename = getFilename(MOCK_DATA_DIRECTORY + "common/" + MOCK_SCHOOL_FILE);
    when(mockSdk.read(anyString())).thenReturn(fromFileWithIDList(filename, schoolIds, key));

    List<GenericEntity> schoolList = client.getSchools(token, schoolIds);

    assertNotNull(schoolList);
    assertEquals(2, schoolList.size());
    ListIterator<GenericEntity> li = schoolList.listIterator();
    while (li.hasNext()) {
        assertTrue(schoolIds.contains(li.next().getString(key)));
    }
}

From source file:com.ibm.asset.trails.action.ShowConfirmation.java

@UserRole(userRole = UserRoleType.READER)
public String deleteSelectedLicenses() {
    List<License> llLicense = getRecon().getLicenseList();
    ListIterator<License> lliLicense = null;
    License llTemp;/*  w  ww .  j av a2 s  .  co  m*/

    List<Report> lReport = new ArrayList<Report>();
    lReport.add(new Report("License baseline", "licenseBaseline"));
    setReportList(lReport);

    if (llLicense == null) {
        llLicense = new ArrayList<License>();
    }

    for (String lsLicenseId : selectedLicenseId) {
        lliLicense = llLicense.listIterator();

        while (lliLicense.hasNext()) {
            llTemp = lliLicense.next();

            if (llTemp.getId().compareTo(Long.valueOf(lsLicenseId)) == 0) {
                lliLicense.remove();
                break;
            }
        }
    }

    getRecon().setLicenseList(llLicense);
    recon.setAutomated(automated);
    recon.setManual(manual);
    recon.setRunon(runon);
    if (getMaxLicenses() != null && getMaxLicenses().trim().length() > 0) {
        recon.setMaxLicenses(new Integer(maxLicenses));
    }
    recon.setPer(per);

    return "license";
}

From source file:org.apache.jackrabbit.core.integration.daily.ItemStateHierarchyManagerDeadlockTest.java

public void runDeadlockTest() {
    long start = System.currentTimeMillis();
    List threads = new ArrayList();
    for (int instanceIndex = 0; instanceIndex < g_numThreads; instanceIndex++) {
        final int index = instanceIndex;
        Thread t = new Thread(new Runnable() {

            public void run() {
                for (int rounds = 0; rounds < 2; rounds++) {
                    if (index % 2 == 0) {
                        removeNodesUnderInvRootNode();
                    }/*from ww w.ja  va2s  . c  om*/
                    createNodesUnderInvRootNode();
                    retrieveNodesUnderInvRootNode();
                    if (index % 2 != 0) {
                        removeNodesUnderInvRootNode();
                    }
                }
            }

        });
        threads.add(t);
        t.start();
    }

    try {
        Iterator it = threads.listIterator();
        while (it.hasNext()) {
            Thread t = (Thread) it.next();
            t.join();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("Duration for run: " + (System.currentTimeMillis() - start) / 1000 + "s");
}

From source file:net.sf.jasperreports.engine.analytics.dataset.MultiAxisDataService.java

protected BucketDefinition createServiceBucket(DataAxisLevel level, byte evaluation) throws JRException {
    DataLevelBucket bucket = level.getBucket();
    Class<?> valueClass = bucket.getValueClass();

    Comparator<Object> comparator = null;
    JRExpression comparatorExpression = bucket.getComparatorExpression();
    if (comparatorExpression != null) {
        comparator = (Comparator<Object>) serviceContext.getExpressionEvaluator().evaluate(comparatorExpression,
                evaluation);/*w  w w  . j  a  v  a  2 s. co m*/
    }

    BucketDefinition bucketDefinition;
    List<DataLevelBucketProperty> bucketProperties = bucket.getBucketProperties();
    if (bucket.getLabelExpression() != null || (bucketProperties != null && !bucketProperties.isEmpty())) {
        // wrapping values in a ValuePropertiesWrapper in order to store property values
        Map<String, Integer> propertyIndexes = new LinkedHashMap<String, Integer>();
        for (ListIterator<DataLevelBucketProperty> it = bucketProperties.listIterator(); it.hasNext();) {
            DataLevelBucketProperty bucketProperty = it.next();
            propertyIndexes.put(bucketProperty.getName(), it.previousIndex());
        }
        axisLevelBucketPropertyIndexes.put(level, propertyIndexes);

        bucketDefinition = new PropertiesWrapperBucketDefintion(comparator, bucket.getOrder(),
                CrosstabTotalPositionEnum.START);
    } else {
        bucketDefinition = new BucketDefinition(valueClass, null, comparator, bucket.getOrder(),
                CrosstabTotalPositionEnum.START);
    }

    return bucketDefinition;
}

From source file:com.gargoylesoftware.htmlunit.WebTestCase.java

/**
 * @param expectedAlerts the list of the expected alerts
 * @return the script to be included at the beginning of the generated HTML file
 * @throws IOException in case of problem
 *///from  w w  w.  j  a  v a 2 s.com
private String createInstrumentationScript(final List<String> expectedAlerts) throws IOException {
    // generate the js code
    final String baseJS = getFileContent("alertVerifier.js");

    final StringBuilder sb = new StringBuilder();
    sb.append("\n<script type='text/javascript'>\n");
    sb.append("var htmlunitReserved_tab = [");
    for (final ListIterator<String> iter = expectedAlerts.listIterator(); iter.hasNext();) {
        if (iter.hasPrevious()) {
            sb.append(", ");
        }
        String message = iter.next();
        message = StringUtils.replace(message, "\\", "\\\\");
        message = message.replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r");
        sb.append("{expected: \"").append(message).append("\"}");
    }
    sb.append("];\n\n");
    sb.append(baseJS);
    sb.append("</script>\n");
    return sb.toString();
}

From source file:com.oneops.ops.dao.PerfDataAccessor.java

/**
 * Gets the perf data table./*ww w. j  a v  a2  s  . c o  m*/
 *
 * @param req the req
 * @return the perf data table
 */
@SuppressWarnings("unchecked")
public String getPerfDataTable(PerfDataRequest req) {

    Long start = Long.valueOf(req.getStart());
    Long end = Long.valueOf(req.getEnd());
    int maxColumns = (int) (end - start);
    String jsonOut = "";

    try {
        long startTime = System.currentTimeMillis();
        String stat = "rra-average";
        if (req.getStat_function() != null) {
            stat = "rra-" + req.getStat_function();
        }

        String rra = getRraByStat(stat, req.getStep());
        int step = alignRraStep(req.getStep());

        MultigetSliceQuery<byte[], Long, Double> multigetSliceQuery = HFactory
                .createMultigetSliceQuery(keyspace, bytesSerializer, longSerializer, doubleSerializer);
        multigetSliceQuery.setColumnFamily(DATA_CF);
        List<byte[]> keys = new ArrayList<>();
        StringBuilder keyString = new StringBuilder("");
        for (int i = 0; i < req.getMetrics().length; i++) {
            String metricDs = req.getMetrics()[i];
            String key = Long.valueOf(req.getCi_id()).toString() + ":" + metricDs + ":" + rra;
            keys.add(key.getBytes());
            keyString.append(" ").append(key);
        }
        multigetSliceQuery.setKeys(keys);
        long adjustedStart = bucketize(start, step);
        multigetSliceQuery.setRange(adjustedStart, end, false, maxColumns);

        multigetSliceQuery.setRange(start, end, false, maxColumns);

        logger.debug("start:" + start + " end:" + end + " for: " + keyString);
        long cassStart = System.currentTimeMillis();

        QueryResult<Rows<byte[], Long, Double>> result = multigetSliceQuery.execute();
        Rows<byte[], Long, Double> rows = result.get();

        long cassEnd = System.currentTimeMillis();
        long cassDuration = cassEnd - cassStart;

        Map<String, Object> valMap = new HashMap<>();
        Map<Long, Integer> timeMap = new TreeMap<>();
        List<String> rowKeys = new ArrayList<>();

        // put the by-metric results into 1 csv-like table
        // (time,metric1,metric2,etc)
        // ... should find faster way to do this, but still 10x faster than
        // gwt DataTable serialization
        int rowCount = 0;
        for (Row<byte[], Long, Double> row : rows) {

            String rowKey = new String(row.getKey());
            Map<Long, Double> colMap = new HashMap<>();
            valMap.put(rowKey, colMap);
            rowKeys.add(rowKey);
            jsonOut += ",\"" + rowKey + "\"";

            List<HColumn<Long, Double>> cols = row.getColumnSlice().getColumns();
            Iterator<HColumn<Long, Double>> listIter = cols.listIterator();
            while (listIter.hasNext()) {
                HColumn<Long, Double> c = (HColumn<Long, Double>) listIter.next();
                colMap.put(c.getName(), c.getValue());
                timeMap.put(c.getName(), 1);
            }
            rowCount++;
        }
        jsonOut += "]\n";

        int resultRowCount = 0;
        for (Long time : timeMap.keySet()) {
            jsonOut += ",[" + time;

            for (int i = 0; i < rowCount; i++) {
                String rowKey = rowKeys.get(i);
                Map<Long, Double> colMap = (Map<Long, Double>) valMap.get(rowKey);
                Double val = colMap.get(time);
                jsonOut += ",";
                // round to 1000ths ; client doesn't need to process all the
                // 10 decimal point resolution
                if (val != null) {
                    jsonOut += Math.round(val * 1000.0) / 1000.0;
                }
            }
            jsonOut += "]\n";
            resultRowCount++;
        }

        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        logger.info("getPerfData took: " + duration + " ms (cass query: " + cassDuration + " ms) returning: "
                + resultRowCount + " rows of " + rowCount + " metrics");

    } catch (HectorException he) {
        he.printStackTrace();
    }

    return jsonOut;
}