Example usage for java.util ArrayList iterator

List of usage examples for java.util ArrayList iterator

Introduction

In this page you can find the example usage for java.util ArrayList iterator.

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this list in proper sequence.

Usage

From source file:com.kircherelectronics.fusedgyroscopeexplorer.sensor.GravitySensor.java

/**
 * Notify observers with new measurements.
 *//*  ww  w .j  a  v  a2 s  .  c  o  m*/
private void notifyGravityObserver() {
    // The iterator is a work around for a concurrency exception...
    GravitySensorObserver observer;

    ArrayList<GravitySensorObserver> notificationList = new ArrayList<GravitySensorObserver>(
            observersAcceleration);

    for (Iterator<GravitySensorObserver> iterator = notificationList.iterator(); iterator.hasNext();) {
        observer = iterator.next();

        observer.onGravitySensorChanged(this.gravity, this.timeStamp);
    }
}

From source file:es.pode.empaquetador.presentacion.avanzado.recursos.crear.archivos.CrearRecursoAvanzadoArchivosControllerImpl.java

public final void eliminar(ActionMapping mapping,
        es.pode.empaquetador.presentacion.avanzado.recursos.crear.archivos.EliminarForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    CrearRecursoArchivosSession sesRecursArch = this.getCrearRecursoArchivosSession(request);
    ArrayList templist = (ArrayList) sesRecursArch.getArchivos();

    String hrefEliminar = form.getHref();
    for (Iterator iter = templist.iterator(); iter.hasNext();) {
        FileVO file = (FileVO) iter.next();
        if (file.getHref().equals(hrefEliminar)) {
            iter.remove();/* ww w  .j av a 2  s.  co m*/
        }

    }

    sesRecursArch.setArchivos(templist);
}

From source file:it.cnr.icar.eric.server.cms.ContentCatalogingServiceManager.java

/**
 * Invokes appropriate Content Management Services for the
 * in the <code>RegistryObject</code>.
 *
 * @param ebRegistryObjectType a <code>RegistryObject</code> value
 * @param ri a <code>RepositoryItem</code> value
 *//*from   w w  w  .ja v a2s.  com*/
public boolean invokeServiceForObject(ServiceInvocationInfo sii, RegistryObjectType ebRegistryObjectType,
        RepositoryItem ri, ServerRequestContext context) throws RegistryException {

    //Cataloging services only apply to Submit/UpdateObjectsRequests
    RegistryRequestType request = context.getCurrentRegistryRequest();
    if (!((request instanceof SubmitObjectsRequest) || (request instanceof UpdateObjectsRequest))) {

        return false;
    }

    if (log.isTraceEnabled()) {
        log.trace("ContentCatalogingServiceManager.invokeServiceForObject()");
    }

    try {
        ContentManagementService cms = (ContentManagementService) sii.getConstructor()
                .newInstance((java.lang.Object[]) null);

        System.err.println("cms: " + cms.getClass().getName());

        ServiceOutput so = null;

        //Note that ri will be null for ExternalLink ro.
        so = cms.invoke(context, new ServiceInput(ebRegistryObjectType, ri), sii.getService(),
                sii.getInvocationController(), context.getUser());

        if (!(so.getOutput() instanceof ServerRequestContext)) {
            throw new InvalidConfigurationException(ServerResourceBundle.getInstance().getString(
                    "message.CatalogingServiceInstanceShouldReturnRequestContext",
                    new Object[] { so.getOutput().getClass().getName() }));
        }

        ServerRequestContext outputContext = (ServerRequestContext) so.getOutput();

        if (outputContext != null) {
            ArrayList<IdentifiableType> list = new ArrayList<IdentifiableType>(
                    outputContext.getTopLevelRegistryObjectTypeMap().values());

            if (log.isDebugEnabled()) {
                Iterator<IdentifiableType> listIter = list.iterator();

                while (listIter.hasNext()) {
                    RegistryObjectType debugRO = (RegistryObjectType) listIter.next();
                    log.debug(debugRO.getId() + "  " + debugRO.getClass().getName() + "  " + debugRO.getName());
                }

                log.debug("Objects found: " + list.size());
            }

            outputContext.checkObjects();

            pm.insert(outputContext, list);
        }
    } catch (RegistryException re) {
        log.error(re, re);
        throw re;
    } catch (Exception e) {
        log.error(e, e);
        throw new RegistryException(e);
    }

    return true;
}

From source file:org.sasabus.export2Freegis.network.DataReadyManager.java

@Override
public void handle(HttpExchange httpExchange) throws IOException {
    long start = System.currentTimeMillis();
    BufferedReader in = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), "UTF-8"));
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(httpExchange.getResponseBody()));
    try {/*from  w  ww . j ava  2s  . co  m*/
        StringBuilder requestStringBuff = new StringBuilder();
        int b;
        while ((b = in.read()) != -1) {
            requestStringBuff.append((char) b);
        }
        Scanner sc = new Scanner(new File(DATAACKNOWLEDGE));
        String rdyackstring = "";
        while (sc.hasNextLine()) {
            rdyackstring += sc.nextLine();
        }
        sc.close();
        SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ");

        Date d = new Date();
        String timestamp = date_date.format(d) + "T" + date_time.format(d);
        timestamp = timestamp.substring(0, timestamp.length() - 2) + ":"
                + timestamp.substring(timestamp.length() - 2);

        rdyackstring = rdyackstring.replaceAll(":timestamp", timestamp);

        httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, rdyackstring.length());
        out.write(rdyackstring);
        out.flush();
        long before_elab = System.currentTimeMillis() - start;
        DataRequestManager teqrequest = new DataRequestManager(this.hostname, this.portnumber);
        String datarequest = teqrequest.datarequest();
        ArrayList<TeqObjects> requestelements = TeqXMLUtils.extractFromXML(datarequest);
        int vtcounter = 0;
        if (!requestelements.isEmpty()) {
            Iterator<TeqObjects> iterator = requestelements.iterator();
            System.out.println("Sending List of Elements!");
            String geoJson = "{\"type\":\"FeatureCollection\",\"features\":[";
            while (iterator.hasNext()) {
                TeqObjects object = iterator.next();
                if (object instanceof VehicleTracking) {
                    geoJson += ((VehicleTracking) object).toGeoJson() + ",";
                    ++vtcounter;
                }
            }
            if (geoJson.charAt(geoJson.length() - 1) == ',') {
                geoJson = geoJson.substring(0, geoJson.length() - 1);
            }
            geoJson += "]}";
            System.out.println(
                    "GeoJson sent! (Nr of elements: " + vtcounter + "/" + requestelements.size() + " )");
            HttpPost subrequest = new HttpPost(DATASEND);

            StringEntity requestEntity = new StringEntity(geoJson,
                    ContentType.create("application/json", "UTF-8"));

            CloseableHttpClient httpClient = HttpClients.createDefault();

            subrequest.setEntity(requestEntity);
            long after_elab = System.currentTimeMillis() - start;
            CloseableHttpResponse response = httpClient.execute(subrequest);
            //System.out.println("Stauts JsonSend Response: " + response.getStatusLine().getStatusCode());
            //System.out.println("Status JsonSend Phrase: " + response.getStatusLine().getReasonPhrase());
            httpClient.close();
            long before_db = System.currentTimeMillis() - start;
            dbmanager.insertIntoDatabase(requestelements);
            System.out.format(
                    "Thread time (ms) : Before elab: %d, After Elab (before http sending): %d, Before db: %d, Total: %d, Thread name: %s, Objects elaborated: %d",
                    before_elab, after_elab, before_db, (System.currentTimeMillis() - start),
                    Thread.currentThread().getName(), requestelements.size());
            System.out.println("");
        }

    } catch (IOException e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
        System.exit(-1);
        return;
    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
        if (httpExchange != null)
            httpExchange.close();
    }
}

From source file:com.servlet.UpdateClaim.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w ww  .  j  av  a2 s . com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    double total = 0;
    //variable declaration
    FileItem item = null;
    String fieldName = "";
    String fieldValue = "";
    String fileName = "";
    boolean isImageExist = false;
    //current sessions
    Employee emp = (Employee) request.getSession().getAttribute("user");
    Claims cla = (Claims) request.getSession().getAttribute("c");

    //bean object
    Claims claims = new Claims();

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {

            List items = upload.parseRequest(request);
            Iterator iterator = items.iterator();

            while (iterator.hasNext()) {
                item = (FileItem) iterator.next();
                if (!item.isFormField()) { // check for regular form field 
                    fileName = item.getName();
                    if (!fileName.equals("")) {

                        String root = getServletContext().getRealPath("/");
                        response.getWriter().write(root);
                        File path = new File(root + "/images/uploads" + File.separator + "Claims"
                                + File.separator + cla.getClaimId());

                        String filePath = "images/uploads/Claims/" + cla.getClaimId() + "/" + fileName;
                        filePath = filePath.replace("\\", "/");
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }
                        //File uploadedFile = new File(path + "/" + fileName);  // for copy file
                        File uploadedFile = new File(path + "/" + fileName); // for copy file

                        item.write(uploadedFile);
                        isImageExist = true;
                        claims.setAttachment(filePath);//save the url in databse

                    } else {
                        isImageExist = false;

                    }

                } else {

                    fieldName = item.getFieldName();// field name of current File item
                    fieldValue = item.getString();
                    if (fieldName.equals("docid")) {
                        claims.setDocId(Integer.parseInt(fieldValue));
                    } else if (fieldName.equals("claim_group")) {
                        claims.setClaimGroup(fieldValue);
                    } else if (fieldName.equals("type_of_claim")) {//bill type
                        claims.setBillType(fieldValue);
                    } else if (fieldName.equals("food_type")) {//meal type
                        claims.setMealType(fieldValue);
                    } else if (fieldName.equals("bill_date")) {
                        claims.setBillDate(fieldValue);
                    } else if (fieldName.equals("amount")) {
                        claims.setAmount(Double.parseDouble(fieldValue));
                    } else if (fieldName.equals("project")) {
                        claims.setProject(fieldValue);
                    } else if (fieldName.equals("description")) {
                        claims.setDescription(fieldValue);
                    } else if (fieldName.equals("employeesId")) {
                        claims.setEmpListId(fieldValue);
                    }
                    ////////////////////

                }

            } //end of while

            DBcon dbcon = new DBcon();
            dbcon.getDbCon();// set up the database connection
            DBCollection coll = dbcon.getData("claims");

            BasicDBObject search = new BasicDBObject("claimid", cla.getClaimId());
            search.append("details.docid", claims.getDocId());

            DBObject obj = claims.toDBObject();//create DBObject from data

            BasicDBObject update = new BasicDBObject();
            update.append("details.$.claimgroup", claims.getClaimGroup());
            update.append("details.$.billtype", claims.getBillType());
            update.append("details.$.mealtype", claims.getMealType());
            update.append("details.$.bill_date", claims.getBillDate());
            update.append("details.$.amount", claims.getAmount());
            update.append("details.$.project", claims.getProject());
            update.append("details.$.description", claims.getDescription());
            update.append("details.$. employeesId", claims.getEmpListId());
            if (isImageExist) {
                update.append("details.$.attachment", claims.getAttachment());
            }

            BasicDBObject push = new BasicDBObject("$set", update);
            dbcon.updateData("claims", search, push);//update the new document 

            DBCursor cursor = coll.find(search);
            DBObject findMainObject = cursor.next();
            Claims mainClaimObject = Claims.fromDBObject2(findMainObject);//create a main claim object
            ArrayList list = mainClaimObject.getDetails();

            Iterator<BasicDBObject> intI = list.iterator();
            while (intI.hasNext()) {
                BasicDBObject o = intI.next();
                Claims cl = Claims.fromDBObject(o);
                total += cl.getAmount();
            }

            mainClaimObject.setTotal(total);//update the total claim amount*/
            DBObject mainObject = mainClaimObject.toDBObject2();
            dbcon.updateData("claims", search, mainObject);//update the new document    
            response.sendRedirect("home_page_claim_add.jsp");

        } catch (FileUploadException e) {

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

            e.printStackTrace();
        }

    }
}

From source file:org.emr.intercepter.RequestInterceptor.java

private void testBean() {
    {//from   www .j  ava  2s. c om
        // LOGINBEAN
        ArrayList<FactoryBean> loginBean = model.getBeanList(new LoginBean());
        if (loginBean != null) {
            Iterator<FactoryBean> lBean = (Iterator<FactoryBean>) loginBean.iterator();
            while (lBean.hasNext()) {
                System.out.println(" login : " + ((LoginBean) lBean.next()).getUsername());
            }
        }
    }
    {
        // PROFILEBEAN

        ArrayList<FactoryBean> profileBean = model.getBeanList(new ProfileBean());
        if (profileBean != null) {
            Iterator<FactoryBean> lBean = (Iterator<FactoryBean>) profileBean.iterator();
            while (lBean.hasNext()) {
                System.out.println(" profile : " + ((ProfileBean) lBean.next()).getName());
            }
        }
    }
    {
        // MODULEBEAN

        ArrayList<FactoryBean> moduleBean = model.getBeanList(new ModuleBean());
        if (moduleBean != null) {
            Iterator<FactoryBean> lBean = (Iterator<FactoryBean>) moduleBean.iterator();
            while (lBean.hasNext()) {
                Set<EntityBean> set = ((ModuleBean) lBean.next()).getEntityBeanSet();
                Iterator<EntityBean> itr = set.iterator();
                while (itr.hasNext())
                    System.out.println(" module : entity set : name and description "
                            + ((EntityBean) itr.next()).getName());

            }
        }
    }
    {
        // ENTITYBEAN

        ArrayList<FactoryBean> entityBean = model.getBeanList(new EntityBean());
        if (entityBean != null) {
            Iterator<FactoryBean> lBean = (Iterator<FactoryBean>) entityBean.iterator();
            while (lBean.hasNext()) {
                System.out.println(" entity : " + ((EntityBean) lBean.next()).getName());
            }
        }
    }
    {
        // SUBENTITYBEAN

        ArrayList<FactoryBean> entityBean = model.getBeanList(new SubEntityBean());
        if (entityBean != null) {
            Iterator<FactoryBean> lBean = (Iterator<FactoryBean>) entityBean.iterator();
            while (lBean.hasNext()) {
                System.out.println(" entity : " + ((SubEntityBean) lBean.next()).getName());
            }
        }
    }
    {
        // LOGINPROFILEBEAN

        ArrayList<FactoryBean> entityBean = model.getBeanList(new LoginProfileBean());
        if (entityBean != null) {
            Iterator<FactoryBean> lBean = (Iterator<FactoryBean>) entityBean.iterator();
            while (lBean.hasNext()) {
                System.out.println(
                        " login profile : profile id  : " + ((LoginProfileBean) lBean.next()).getProfileId());
            }
        }
    }
    {
        // SUBENTITYBEAN

        ArrayList<FactoryBean> entityBean = model.getBeanList(new ProfileSubEntityMappingBean());
        if (entityBean != null) {
            Iterator<FactoryBean> lBean = (Iterator<FactoryBean>) entityBean.iterator();
            while (lBean.hasNext()) {
                System.out.println(" profile entity mapping with subentity id  : "
                        + ((ProfileSubEntityMappingBean) lBean.next()).getSubEntityId());
            }
        }
    }

}

From source file:controller.administrator.DriverController.java

@RequestMapping(value = "/ViewAllDriver", method = RequestMethod.GET)
public ModelAndView viewAll() {
    ArrayList<Object[]> arraydriver = new ArrayList<Object[]>();
    ModelAndView model = new ModelAndView("DisplayAllDriver");
    arraydriver = driverservice.displayall();
    model.addObject("drivers", arraydriver);
    Iterator it = arraydriver.iterator();
    while (it.hasNext()) {
        Object[] arraydriverinfo = (Object[]) it.next();
        // System.out.print(arraydriverinfo[0]+"  "+arraydriverinfo[1]+" "+arraydriverinfo[11]);
    }/*from ww w .j av a 2  s.co m*/

    return model;
}

From source file:com.projity.grouping.core.model.AssignmentNodeModel.java

public void paste(Node parent, List nodes, int position, int actionType) {
    super.paste(parent, nodes, position, actionType);
    ArrayList roots = new ArrayList();
    HierarchyUtils.extractParents(nodes, roots);
    final List freeAssignments = new ArrayList();
    for (Iterator i = roots.iterator(); i.hasNext();)
        hierarchy.visitLeaves((Node) i.next(), new Closure() {
            public void execute(Object o) {
                Node node = (Node) o;
                if (node.getImpl() instanceof Assignment) {
                    Assignment assignment = (Assignment) node.getImpl();
                    Node parent = (Node) node.getParent();
                    if (parent.getImpl() instanceof NormalTask) {
                        NormalTask task = (NormalTask) parent.getImpl();
                        if (task.findAssignment(assignment.getResource()) == null) {
                            freeAssignments.add(node);
                        }/*from  w  ww  . j a  va 2 s.co m*/
                    }
                }
            }
        });
    for (Iterator i = freeAssignments.iterator(); i.hasNext();) {
        Node node = (Node) i.next();
        node.removeFromParent();
        System.out.println("restoring assignment: " + node.getImpl());
        AssignmentService.getInstance().connect(node, this, isUndo(actionType));
    }

}

From source file:com.concursive.connect.cms.portal.dao.DashboardTemplateList.java

private void parseLibrary(XMLUtils library) {
    LOG.debug("objectType=" + objectType);
    LOG.debug("has xml? " + (library != null));
    if (LOG.isTraceEnabled()) {
        LOG.trace(library.toString());/*from   w ww .j a  v  a 2  s  . co  m*/
    }

    // Use XPath for querying xml elements
    XPath xpath = XPathFactory.newInstance().newXPath();

    // Build a list of dashboard pages
    ArrayList<Element> pageElements = new ArrayList<Element>();
    XMLUtils.getAllChildren(XMLUtils.getFirstChild(library.getDocumentElement(), objectType), "page",
            pageElements);
    Iterator i = pageElements.iterator();
    int count = 0;
    while (i.hasNext()) {
        ++count;
        Element el = (Element) i.next();
        DashboardTemplate thisTemplate = new DashboardTemplate();
        thisTemplate.setId(count);
        thisTemplate.setName(el.getAttribute("name"));

        // Check for xml included fragments declaration
        // <xml-include fragment="portal-fragments-id"/>
        // NOTE: since the document is being read as a resource, xinclude and xpointer could not be used
        // mainly due to xpointer not being implemented
        try {
            NodeList includeList = (NodeList) xpath.evaluate("row/column/portlet/xml-include", el,
                    XPathConstants.NODESET);
            // XML Include found, so find all the fragments
            for (int nodeIndex = 0; nodeIndex < includeList.getLength(); nodeIndex++) {
                Node xmlInclude = includeList.item(nodeIndex);
                String fragmentId = ((Element) xmlInclude).getAttribute("fragment");

                NodeList fragmentNodeList = (NodeList) xpath.evaluate(
                        "*/fragment[@id=\"" + fragmentId + "\"]/*", library.getDocumentElement(),
                        XPathConstants.NODESET);
                if (LOG.isDebugEnabled() && fragmentNodeList.getLength() == 0) {
                    LOG.error("Could not find fragment with id: " + fragmentId);
                }
                for (int prefIndex = 0; prefIndex < fragmentNodeList.getLength(); prefIndex++) {
                    xmlInclude.getParentNode().appendChild(fragmentNodeList.item(prefIndex).cloneNode(true));
                }
                // Remove the XML Include declaration
                xmlInclude.getParentNode().removeChild(xmlInclude);

            }
        } catch (Exception e) {
            LOG.error("Replace xml fragments", e);
        }

        // Set the completed xml layout
        thisTemplate.setXmlDesign(XMLUtils.toString(el));

        // Check for properties that affect the rendering of the portal page
        if (el.hasAttribute("permission")) {
            thisTemplate.setPermission(el.getAttribute("permission"));
        }
        if (el.hasAttribute("title")) {
            thisTemplate.setTitle(el.getAttribute("title"));
        }
        if (el.hasAttribute("description")) {
            thisTemplate.setDescription(el.getAttribute("description"));
        }
        if (el.hasAttribute("keywords")) {
            thisTemplate.setKeywords(el.getAttribute("keywords"));
        }
        if (el.hasAttribute("category")) {
            thisTemplate.setCategory(el.getAttribute("category"));
        }
        this.add(thisTemplate);
    }
}

From source file:blusunrize.immersiveengineering.api.ApiUtils.java

public static boolean stacksMatchIngredientList(List<IngredientStack> list, NonNullList<ItemStack> stacks) {
    ArrayList<ItemStack> queryList = new ArrayList<ItemStack>(stacks.size());
    for (ItemStack s : stacks)
        if (!s.isEmpty())
            queryList.add(s.copy());//from   w  ww.  j a v a 2  s  . com

    for (IngredientStack ingr : list)
        if (ingr != null) {
            int amount = ingr.inputSize;
            Iterator<ItemStack> it = queryList.iterator();
            while (it.hasNext()) {
                ItemStack query = it.next();
                if (!query.isEmpty()) {
                    if (ingr.matchesItemStackIgnoringSize(query)) {
                        if (query.getCount() > amount) {
                            query.shrink(amount);
                            amount = 0;
                        } else {
                            amount -= query.getCount();
                            query.setCount(0);
                        }
                    }
                    if (query.getCount() <= 0)
                        it.remove();
                    if (amount <= 0)
                        break;
                }
            }
            if (amount > 0)
                return false;
        }
    return true;
}