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:com.bluelotussoftware.apache.commons.fileupload.example.FileUploadServlet.java

/**
 * Processes requests for both HTTP//from   w ww  .  j a  v a  2s.  co  m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    log("isMultipartContent: " + isMultiPart);
    log("Content-Type: " + request.getContentType());
    if (isMultiPart) {

        // Create a factory for disk-based file items
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        /*
         * Set the file size limit in bytes. This should be set as an
         * initialization parameter
         */
        diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB.

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);

        // Parse the request
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            log("Could not parse request", ex);
        }

        PrintWriter out = response.getWriter();
        out.print("<html><head><title>SUCCESS</title></head><body><h1>DONE!</h1>");

        ListIterator li = items.listIterator();
        while (li.hasNext()) {
            FileItem fileItem = (FileItem) li.next();
            if (fileItem.isFormField()) {
                processFormField(fileItem);
            } else {
                out.append(processUploadedFile(fileItem));
            }
        }
        out.print("</body></html>");
        out.flush();
        out.close();

    }
}

From source file:com.amazonaws.services.kinesis.clientlibrary.lib.worker.ShardConsumerTest.java

private void verifyConsumedRecords(List<Record> expectedRecords, List<Record> actualRecords) {
    //@formatter:on
    assertThat(actualRecords.size(), is(equalTo(expectedRecords.size())));
    ListIterator<Record> expectedIter = expectedRecords.listIterator();
    ListIterator<Record> actualIter = actualRecords.listIterator();
    for (int i = 0; i < expectedRecords.size(); ++i) {
        assertThat(actualIter.next(), is(equalTo(expectedIter.next())));
    }/* w  w w  .  ja v a  2 s.c o  m*/
}

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

/**
 * Perform bulk query./*w  w w  . j  av  a2s .  com*/
 *
 * @param inputFile the input file
 * @param outPutFile the out put file
 * @param config the config
 * @param sslResolver the ssl resolver
 */
private static void performBulkQuery(final String inputFile, final String outPutFile,
        final MCCConfiguration config, final SSLResolver sslResolver) {

    List<DNSQueryResult> queriesResults = new ArrayList<DNSQueryResult>();

    List<RequestBean> queriesRequest = new ArrayList<RequestBean>();

    RequestBean request = null;

    String dataStr = null;

    BufferedReader reader = null;

    Writer writer = null;

    try {
        reader = new BufferedReader(new FileReader(inputFile));

        // read the list of queries from input file
        while ((dataStr = reader.readLine()) != null) {

            System.out.println("Processing line - " + dataStr);

            String[] fields = dataStr.split(",");

            if (fields.length > 1) {
                request = new RequestBean();
                request.setCountryCode(fields[0]);
                request.setTn(fields[1]);
                queriesRequest.add(request);
            } else {
                System.err.print("Invalid line in input file - " + dataStr);
            }
        }

        DNSSSLBulkQuery dnsSSLBulkQuery = new DNSSSLBulkQuery();

        queriesResults = dnsSSLBulkQuery.executeBulkQueries(queriesRequest, config, sslResolver);

        Iterator<DNSQueryResult> resultIterator = queriesResults.listIterator();

        writer = new PrintWriter(new FileWriter(outPutFile));

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

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

        while (resultIterator.hasNext()) {
            DNSQueryResult result = resultIterator.next();

            if (result != null) {
                writer.write(result.getCountryCode());
                writer.write(" | ");
                writer.write(result.getTn());
                writer.write(" | ");
                if (result.getRcode() == RCODE.REFUSED) {
                    writer.write(" REFUSED ");
                    writer.write("\n");
                } else if (result.getRcode() == RCODE.NXDOMAIN) {
                    writer.write(" NXDOMAIN ");
                    writer.write("\n");
                } else if (result.getRcode() == RCODE.FORMAT_ERROR) {
                    writer.write(" FORMAT_ERROR ");
                    writer.write("\n");
                } else if (result.getRcode() == RCODE.SERVFAIL) {
                    writer.write(" SERVFAIL ");
                    writer.write("\n");
                } else if (result.getRcode() == RCODE.SERVER_NOT_FOUND) {
                    writer.write(" SERVER_NOT_FOUND ");
                    writer.write("\n");
                } else if (result.getRcode() == RCODE.NO_ERROR) {
                    writer.write("TN match success. Route = ");
                    naptrArray = result.getNaptrArray();
                    naptIt = naptrArray.listIterator();
                    while (naptIt.hasNext()) {
                        String naptrResult = naptIt.next();
                        writer.write(" | " + naptrResult);
                    }
                    writer.write("\n\n");
                } else {
                    writer.write("Unanticipated error: " + result.getRcode()
                            + ".Please contact NeuStar customer support");
                    writer.write("\n");
                }
            }
        }
        writer.flush();
    } catch (Exception e) {
        System.err.println("Exception occured while sending bulk query");
        e.printStackTrace();
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (writer != null) {
                writer.close();
            }
        } catch (IOException e) {
            System.err.println("Problem occured while closing output stream.");
        }
    }
}

From source file:com.amazonaws.services.kinesis.clientlibrary.lib.worker.ProcessTask.java

/**
 * Scans a list of records to filter out records up to and including the most recent checkpoint value and to get
 * the greatest extended sequence number from the retained records. Also emits metrics about the records.
 *
 * @param scope metrics scope to emit metrics into
 * @param records list of records to scan and change in-place as needed
 * @param lastCheckpointValue the most recent checkpoint value
 * @param lastLargestPermittedCheckpointValue previous largest permitted checkpoint value
 * @return the largest extended sequence number among the retained records
 *//*from   ww w. jav  a2 s. co m*/
private ExtendedSequenceNumber filterAndGetMaxExtendedSequenceNumber(IMetricsScope scope, List<Record> records,
        final ExtendedSequenceNumber lastCheckpointValue,
        final ExtendedSequenceNumber lastLargestPermittedCheckpointValue) {
    ExtendedSequenceNumber largestExtendedSequenceNumber = lastLargestPermittedCheckpointValue;
    ListIterator<Record> recordIterator = records.listIterator();
    while (recordIterator.hasNext()) {
        Record record = recordIterator.next();
        ExtendedSequenceNumber extendedSequenceNumber = new ExtendedSequenceNumber(record.getSequenceNumber(),
                record instanceof UserRecord ? ((UserRecord) record).getSubSequenceNumber() : null);

        if (extendedSequenceNumber.compareTo(lastCheckpointValue) <= 0) {
            recordIterator.remove();
            LOG.debug("removing record with ESN " + extendedSequenceNumber
                    + " because the ESN is <= checkpoint (" + lastCheckpointValue + ")");
            continue;
        }

        if (largestExtendedSequenceNumber == null
                || largestExtendedSequenceNumber.compareTo(extendedSequenceNumber) < 0) {
            largestExtendedSequenceNumber = extendedSequenceNumber;
        }

        scope.addData(DATA_BYTES_PROCESSED_METRIC, record.getData().limit(), StandardUnit.Bytes,
                MetricsLevel.SUMMARY);
    }
    return largestExtendedSequenceNumber;
}

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

private void placeVoidNodes(List list) {
    ListIterator i = list.listIterator();
    while (i.hasNext()) {
        GraphicNode gnode = (GraphicNode) i.next();
        //if (!gnode.isGroup()){ //Already disabled if sorters or groupers are working
        placeVoidNodes(i, gnode.getNode());
        //}/*  www . j a  va  2 s  .co m*/
    }
    placeVoidNodes(i, (Node) refCache.getModel().getRoot());
}

From source file:com.mirth.connect.server.util.DatabaseConnection.java

public CachedRowSet executeUpdateAndGetGeneratedKeys(String expression, List<Object> parameters)
        throws SQLException {
    PreparedStatement statement = null;

    try {/*  w  w  w.  j a  v  a2  s . c om*/
        statement = connection.prepareStatement(expression, Statement.RETURN_GENERATED_KEYS);
        logger.debug("executing prepared statement:\n" + expression);

        ListIterator<Object> iterator = parameters.listIterator();

        while (iterator.hasNext()) {
            int index = iterator.nextIndex() + 1;
            Object value = iterator.next();
            logger.debug("adding parameter: index=" + index + ", value=" + value);
            statement.setObject(index, value);
        }

        statement.executeUpdate();
        CachedRowSetImpl crs = new CachedRowSetImpl();
        crs.populate(statement.getGeneratedKeys());
        return crs;
    } catch (SQLException e) {
        throw e;
    } finally {
        DbUtils.closeQuietly(statement);
    }
}

From source file:nl.armatiek.xslweb.web.servlet.XSLWebServlet.java

@SuppressWarnings("unchecked")
@Override/*from  w  w w.ja  v a  2 s  . c  o  m*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    OutputStream respOs = resp.getOutputStream();
    WebApp webApp = null;
    try {
        webApp = (WebApp) req.getAttribute(Definitions.ATTRNAME_WEBAPP);
        if (webApp.isClosed()) {
            resp.resetBuffer();
            resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            resp.setContentType("text/html; charset=UTF-8");
            Writer w = new OutputStreamWriter(respOs, "UTF-8");
            w.write("<html><body><h1>Service temporarily unavailable</h1></body></html>");
            return;
        }
        executeRequest(webApp, req, resp, respOs);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        if (webApp != null && webApp.getDevelopmentMode()) {
            resp.setContentType("text/plain; charset=UTF-8");
            e.printStackTrace(new PrintStream(respOs));
        } else if (!resp.isCommitted()) {
            resp.resetBuffer();
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.setContentType("text/html; charset=UTF-8");
            Writer w = new OutputStreamWriter(respOs, "UTF-8");
            w.write("<html><body><h1>Internal Server Error</h1></body></html>");
        }
    } finally {
        // Delete any registered temporary files:
        try {
            List<File> tempFiles = (List<File>) req.getAttribute(Definitions.ATTRNAME_TEMPFILES);
            if (tempFiles != null) {
                ListIterator<File> li = tempFiles.listIterator();
                while (li.hasNext()) {
                    File file;
                    if ((file = li.next()) != null) {
                        FileUtils.deleteQuietly(file);
                    }
                }
            }
        } catch (Exception se) {
            logger.error("Error deleting registered temporary files", se);
        }

        // Close any closeables:
        try {
            List<Closeable> closeables = (List<Closeable>) req.getAttribute("xslweb-closeables");
            if (closeables != null) {
                ListIterator<Closeable> li = closeables.listIterator(closeables.size());
                while (li.hasPrevious()) {
                    li.previous().close();
                }
            }
        } catch (Exception se) {
            logger.error("Could not close Closeable", se);
        }
    }
}

From source file:com.qualogy.qafe.presentation.EventHandlerImpl.java

private Collection<BuiltInFunction> handleEventItems(List<EventItem> eventItems, ApplicationContext context,
        Event event, DataIdentifier dataId, EventData eventData) throws ExternalException {
    Collection<BuiltInFunction> builtInList = new ArrayList<BuiltInFunction>();
    if (eventItems != null) {
        ListIterator<EventItem> itrEventItem = eventItems.listIterator();
        while (itrEventItem.hasNext()) {
            EventItem eventItem = itrEventItem.next();
            try {
                boolean stopProcessing = EventItemExecutor.getInstance().execute(eventItem, context, event,
                        eventData, builtInList, this, dataId);
                if (stopProcessing) {
                    break;
                }/*from  w w  w. j  ava  2  s. c  o m*/
            } catch (ReturnBuiltInException e) {
                break;
            } catch (ExternalException e) {
                ErrorResult errorResult = EventErrorProcessor.processError(itrEventItem, eventItem, context,
                        dataId, e, eventData);
                boolean rethrow = (errorResult.getExternalException() != null);
                if (rethrow) {
                    throw errorResult.getExternalException();
                } else if (errorResult.hasItems()) {
                    List<EventItem> exceptionHandlingEventItems = new ArrayList<EventItem>();
                    for (Item item : errorResult.getItems()) {
                        if (item instanceof EventItem) {
                            exceptionHandlingEventItems.add((EventItem) item);
                        }
                    }
                    Collection<BuiltInFunction> exceptionHandlingBuiltInList = handleEventItems(
                            exceptionHandlingEventItems, context, event, dataId, eventData);
                    builtInList.addAll(exceptionHandlingBuiltInList);
                }
            }
        }
    }
    return builtInList;
}

From source file:org.broadleafcommerce.core.order.dao.OrderDaoImpl.java

@Override
@SuppressWarnings("unchecked")
public Order readNamedOrderForCustomer(final Customer customer, final String name) {
    final Query query = em.createNamedQuery("BC_READ_NAMED_ORDER_FOR_CUSTOMER");
    query.setParameter("customerId", customer.getId());
    query.setParameter("orderStatus", OrderStatus.NAMED.getType());
    query.setParameter("orderName", name);
    List<Order> orders = query.getResultList();

    // Filter out orders that don't match the current locale (if one is set)
    if (BroadleafRequestContext.getBroadleafRequestContext() != null) {
        ListIterator<Order> iter = orders.listIterator();
        while (iter.hasNext()) {
            Locale locale = BroadleafRequestContext.getBroadleafRequestContext().getLocale();
            Order order = iter.next();/*from w w w .  j a va 2  s.c  o m*/
            if (locale != null && !locale.equals(order.getLocale())) {
                iter.remove();
            }
        }
    }

    // Apply any additional filters that extension modules have registered
    if (orders != null && !orders.isEmpty() && extensionManager != null) {
        extensionManager.getProxy().applyAdditionalOrderLookupFilter(customer, name, orders);
    }

    return orders == null || orders.isEmpty() ? null : orders.get(0);
}

From source file:com.caricah.iotracah.datastore.ignitecache.internal.impl.SubscriptionFilterHandler.java

public Observable<IotSubscriptionFilter> matchTopicFilterTree(String partitionId,
        List<String> topicNavigationRoute) {

    return Observable.create(observer -> {

        Set<IotSubscriptionFilterKey> topicFilterKeys = new HashSet<>();

        ListIterator<String> pathIterator = topicNavigationRoute.listIterator();

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

        while (pathIterator.hasNext()) {

            String name = pathIterator.next();

            List<String> slWildCardList = new ArrayList<>(growingTitles);

            if (pathIterator.hasNext()) {
                //We deal with wildcard.
                slWildCardList.add(Constant.MULTI_LEVEL_WILDCARD);
                topicFilterKeys.add(keyFromList(partitionId, slWildCardList));

            } else {

                slWildCardList.add(Constant.SINGLE_LEVEL_WILDCARD);
                topicFilterKeys.add(keyFromList(partitionId, slWildCardList));

                slWildCardList.add(Constant.SINGLE_LEVEL_WILDCARD);
                topicFilterKeys.add(keyFromList(partitionId, slWildCardList));

                slWildCardList.remove(slWildCardList.size() - 1);
                slWildCardList.remove(slWildCardList.size() - 1);

                //we deal with full topic
                slWildCardList.add(name);
            }//from   w w  w  .  j  av  a  2s .c  o  m

            List<String> reverseSlWildCardList = new ArrayList<>(slWildCardList);

            growingTitles.add(name);

            int sizeOfTopic = slWildCardList.size() - 1;

            for (int i = 0; i <= sizeOfTopic; i++) {

                if (i < sizeOfTopic) {
                    int reverseIndex = sizeOfTopic - i;

                    slWildCardList.set(i, Constant.SINGLE_LEVEL_WILDCARD);
                    reverseSlWildCardList.set(reverseIndex, Constant.SINGLE_LEVEL_WILDCARD);

                    topicFilterKeys.add(keyFromList(partitionId, slWildCardList));
                    topicFilterKeys.add(keyFromList(partitionId, reverseSlWildCardList));

                } else {

                    if (!pathIterator.hasNext()) {

                        slWildCardList.set(i, Constant.SINGLE_LEVEL_WILDCARD);
                        topicFilterKeys.add(keyFromList(partitionId, slWildCardList));

                        slWildCardList.add(Constant.SINGLE_LEVEL_WILDCARD);
                        topicFilterKeys.add(keyFromList(partitionId, slWildCardList));

                        slWildCardList.set(slWildCardList.size() - 1, Constant.MULTI_LEVEL_WILDCARD);
                        topicFilterKeys.add(keyFromList(partitionId, slWildCardList));

                    }

                }
            }

        }

        topicFilterKeys.add(keyFromList(partitionId, growingTitles));

        growingTitles.add(Constant.SINGLE_LEVEL_WILDCARD);
        topicFilterKeys.add(keyFromList(partitionId, growingTitles));

        growingTitles.set(growingTitles.size() - 1, Constant.MULTI_LEVEL_WILDCARD);
        topicFilterKeys.add(keyFromList(partitionId, growingTitles));

        growingTitles.remove(growingTitles.size() - 1);

        growingTitles.set(growingTitles.size() - 1, Constant.SINGLE_LEVEL_WILDCARD);
        topicFilterKeys.add(keyFromList(partitionId, growingTitles));

        growingTitles.set(growingTitles.size() - 1, Constant.MULTI_LEVEL_WILDCARD);
        topicFilterKeys.add(keyFromList(partitionId, growingTitles));

        //Add lost wildcard
        getBySet(topicFilterKeys).subscribe(observer::onNext, observer::onError, observer::onCompleted);

    });

}