Example usage for java.util ArrayList remove

List of usage examples for java.util ArrayList remove

Introduction

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

Prototype

public boolean remove(Object o) 

Source Link

Document

Removes the first occurrence of the specified element from this list, if it is present.

Usage

From source file:org.ala.repository.Validator.java

/**
 * Validate a DC file (parsed into list of String[])
 *
 * @param lines/* w ww .jav a2  s. c  om*/
 * @throws IllegalArgumentException
 * @throws NoSuchFieldError
 * @throws Exception
 */
protected void validateRdfFile(List<String[]> lines)
        throws IllegalArgumentException, NoSuchFieldError, Exception {
    // initialise requiredRdfFields
    ArrayList<String> requiredRdfFields = new ArrayList<String>();
    requiredRdfFields.add(Field.SCI_NAME.name);

    for (String[] data : lines) {
        logger.debug("RDF entries (" + data.length + ") = " + StringUtils.join(data, "|"));
        Assert.isTrue(data.length == FileType.RDF.getFieldCount(), "RDF Entry not expected size of "
                + FileType.RDF.getFieldCount() + ", got " + data.length + " - " + StringUtils.join(data, "|"));

        if (data[1].endsWith(Field.SCI_NAME.name)) {
            // Check hasScientificName
            requiredRdfFields.remove(Field.SCI_NAME.name);
            Assert.isTrue(data[2].length() > 0, Field.SCI_NAME.name + " is empty");
        }
    }

    if (!requiredRdfFields.isEmpty()) {
        throw new NoSuchFieldError("Required fields not found: " + StringUtils.join(requiredRdfFields, ", "));
    }
}

From source file:org.safegees.safegees.gui.view.MainActivity.java

private void start() {
    if (DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)) != null
            && DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)).length() > 0) {
        shareDataWithServer();//from  w  ww  .j a  va 2s .c  om
    } else {

        /* TEST
        if(DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)) != null && DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)).length()>0){
        launchMainActivity();
        }else{
        //Start the loggin for result
        Intent loginInt = new Intent(this, LoginActivity.class);
        startActivityForResult(loginInt, 1);
        }*/

        if (Connectivity.isNetworkAvaiable(this) || StoredDataQuequesManager.getAppUsersMap(this).size() != 0) {

            final MainActivity mainActivity = this;

            //Download data
            this.adviceUser.setText(getResources().getString(R.string.splash_advice_download_info_hub));

            //Test
            //Not here at final
            final WebView webView = (WebView) this.findViewById(R.id.webview_info_pre_cache);
            final ArrayList<String> infoWebUrls = WebViewInfoWebDownloadController.getInfoUrlsArrayList();
            webView.setWebViewClient(new WebViewClient() {

                @Override
                public void onPageFinished(WebView view, String url) {
                    if (infoWebUrls.size() > 0) {
                        String nextUrl = infoWebUrls.get(0);
                        infoWebUrls.remove(nextUrl);
                        webView.loadUrl(nextUrl);
                    } else {
                        //Only one time
                        DATA_STORAGE.putBoolean(mainActivity.getResources().getString(R.string.KEY_INFO_WEB),
                                true);
                        //Start the loggin for result
                        Intent loginInt = new Intent(mainActivity, LoginActivity.class);
                        startActivityForResult(loginInt, 1);
                    }
                }
            });

            String nextUrl = infoWebUrls.get(0);
            infoWebUrls.remove(nextUrl);
            webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setWebChromeClient(new WebChromeClient());

            if (StoredDataQuequesManager.getAppUsersMap(mainActivity).size() == 0
                    && !DATA_STORAGE.getBoolean(getResources().getString(R.string.KEY_INFO_WEB))) {
                webView.loadUrl(nextUrl);
            } else {
                if (DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL)) != null
                        && DATA_STORAGE.getString(getResources().getString(R.string.KEY_USER_MAIL))
                                .length() > 0) {
                    launchMainActivity();
                } else {
                    //Start the loggin for result
                    Intent loginInt = new Intent(mainActivity, LoginActivity.class);
                    startActivityForResult(loginInt, 1);
                }
            }

        } else {
            setNoInternetAdvice(this);
        }
    }
}

From source file:com.provenance.cloudprovenance.policyengine.cond.XPathProvenanceFunction.java

public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {

    if (xpathUtility == null) {
        loadSpringBean();//from w  w w .j a v a 2s . c o  m
    }

    logger.debug(" Loaded bean " + this.getXpathUtility());

    // Evaluate the arguments
    AttributeValue[] argValues = new AttributeValue[inputs.size()];

    logger.debug("Evaluatable list size: " + inputs.size() + "  ");

    // TODO - Explore how this statement is executed ....
    EvaluationResult result = evalArgs(inputs, context, argValues);

    XPathAttribute xpathAttribute = ((XPathAttribute) argValues[0]);
    String xpathValue = xpathAttribute.getValue();
    String category = xpathAttribute.getXPathCategory();
    String attributeId = xpathAttribute.getAttributeId();

    switch (getFunctionId()) {
    case ID_XPATH__PROVENANCE_S_ID_MATCH: {
        boolean evalutionResult = false;
        logger.info("xpath Value: " + xpathValue + ", category: " + category);

        try {
            evalutionResult = xpathUtility
                    .evaluateIdWithStore(xpathUtility.constructXpathExpression(xpathValue));
        } catch (XMLDBException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        logger.info("The result is: " + evalutionResult);

        return EvaluationResult.getInstance(evalutionResult);
    }

    // Check for dynamic variable
    case ID_XPATH__PROVENANCE_D_ID_MATCH: {

        logger.debug("Attribute type ==> " + argValues[0] + " XPATH-D-ID-MATCH");

        // Handle new variable type
        if (category.equals(XPATH_PROVENANCE_DYNAMIC_VARIABLE_CATEGORY)) {

            logger.info("Dynamic variable detected, adding it to the store ");

            // Add the variable reference to the Variable holder
            DynamicVariableHolder.getDynamicVariableHolderInstance().addDynamicVar(xpathValue, null);

            return EvaluationResult.getInstance(true);
        }

        // Handle Ref variable
        AbstractRequestCtx ctx = context.getRequestCtx();
        Set<Attributes> attCtxList = ctx.getAttributesSet();

        logger.info("attCtxList size: " + attCtxList.size());

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

        for (Attributes att : attCtxList) {
            logger.debug("Context Category: " + att.getCategory() + "; expected category: " + category);

            if (att.getCategory().toString().equals(category)) {
                Node content = att.getContent();

                if (content != null)
                    logger.debug("Context content: " + att.getContent().toString());

                if (att.getAttributes().size() > 0) {
                    Set<Attribute> attc = att.getAttributes();

                    for (Attribute tmpSubAtt : attc) {
                        logger.debug("Request Att type: " + tmpSubAtt.getType());
                        logger.debug("Request Att ID: " + tmpSubAtt.getId());

                        AttributeValue attVal = tmpSubAtt.getValue();
                        logger.debug("Request Attribute content: " + attVal.encode());

                        // check if the value is single or multiple
                        if (attVal.encode().contains(";")) {

                            if (multipleEntriesInputMap.containsKey(category)) {

                                // check if the content has been removed, if
                                // so remove the key
                                if (multipleEntriesInputMap.get(category).size() == 0) {

                                    logger.debug("Old key does not contain value, spliting contents again");

                                    String tokenizeInput[] = attVal.encode().split(";");
                                    ArrayList<String> tokenizedArrayList = new ArrayList<String>(
                                            new ArrayList<String>(Arrays.asList(tokenizeInput)));

                                    // add the first value to the list
                                    attributeMatchedValuesList.add(tokenizedArrayList.get(0));

                                    tokenizedArrayList.remove(0);
                                    // add the remaining to the list

                                    multipleEntriesInputMap.put(category, tokenizedArrayList);
                                }

                                ArrayList<String> currentList = multipleEntriesInputMap.get(category);
                                attributeMatchedValuesList.add(currentList.get(0));
                                currentList.remove(0);

                            } else {
                                logger.debug("Contains multiple values, spliting contents");
                                String tokenizeInput[] = attVal.encode().split(";");
                                ArrayList<String> tokenizedArrayList = new ArrayList<String>(
                                        new ArrayList<String>(Arrays.asList(tokenizeInput)));

                                // add the first value to the list

                                attributeMatchedValuesList.add(tokenizedArrayList.get(0));

                                tokenizedArrayList.remove(0);
                                // add the remaining to the list

                                multipleEntriesInputMap.put(category, tokenizedArrayList);

                            }

                        } else {

                            attributeMatchedValuesList.add(attVal.encode());
                        }
                    }
                }
                break;
            }
        }

        if (attributeMatchedValuesList.size() > 0) {
            logger.debug("D-var ref value extracted: " + attributeMatchedValuesList.size());

            // Check it against the store .....
            for (int i = 0; i < attributeMatchedValuesList.size(); i++) {
                boolean evalutionResult = false;
                String variableValue = attributeMatchedValuesList.get(i);

                try {
                    // check if it is not a s-ref variable, and only a d-ref
                    if (attributeId.equals(XPATH_PROVENANCE_D_DYNAMIC_VARIABLE_CATEGORY)) {

                        // evaluate the value against the store
                        logger.info("D-variable detected matching against the store ");

                        evalutionResult = xpathUtility
                                .evaluateIdWithStore(xpathUtility.constructXpathExpression(variableValue));

                        if (evalutionResult == false) {
                            logger.warn("Match against the store failed !");

                            return EvaluationResult.getInstance(false);
                        } else {

                            logger.debug("Adding to d-dynamic variable store: " + xpathValue + " ..."
                                    + Arrays.toString(attributeMatchedValuesList.toArray()));
                            DynamicVariableHolder.getDynamicVariableHolderInstance().addDynamicVar(xpathValue,
                                    attributeMatchedValuesList);
                            return EvaluationResult.getInstance(true);

                        }

                    } else if (attributeId.equals(XPATH_PROVENANCE_S_DYNAMIC_VARIABLE_CATEGORY)) {

                        // evaluate the value against the store
                        logger.info("S-variable detecte Adding to d-dynamic variable store: " + xpathValue
                                + " ..." + Arrays.toString(attributeMatchedValuesList.toArray()));

                        DynamicVariableHolder.getDynamicVariableHolderInstance().addDynamicVar(xpathValue,
                                attributeMatchedValuesList);
                        return EvaluationResult.getInstance(true);
                    }

                } catch (XMLDBException e) {
                    e.printStackTrace();
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                } catch (ParserConfigurationException e) {
                    e.printStackTrace();
                } catch (SAXException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } else {
            logger.warn("No d-var ref variable found !!!");
            return EvaluationResult.getInstance(false);
        }
    }
    default:
        logger.warn("No match found!!!");
        return EvaluationResult.getInstance(false);
    }
}

From source file:com.projity.pm.graphic.spreadsheet.common.CommonSpreadSheet.java

public ArrayList getSelectableFields() {
    List fa = getFieldArray();//from  w w  w  .ja  v  a  2 s.c  om
    ArrayList fields = new ArrayList(fa.size());
    fields.addAll(fa);
    if (fields.size() > 0)
        fields.remove(0); //ID not selectable
    return fields;
}

From source file:com.atinternet.tracker.Builder.java

private Param getRefOrRefstoreParam(String key, ArrayList<Param> completeBuffer) {
    Param ref = null;/*from  w  ww .  ja  v a  2s. co m*/
    ArrayList<int[]> refParamPositions = Tool.findParameterPosition(key, completeBuffer);
    int indexRef = refParamPositions.isEmpty() ? -1 : refParamPositions.get(refParamPositions.size() - 1)[1];

    if (indexRef != -1) {
        ref = completeBuffer.remove(indexRef);
        if (ref.getOptions() != null && ref.getOptions().getRelativePosition() != last
                && ref.getOptions().getRelativePosition() != none) {
            Tool.executeCallback(tracker.getListener(), CallbackType.warning,
                    key + "= parameter will be put in last position");
        }
    }

    return ref;
}

From source file:com.emc.plants.web.servlets.ShoppingServlet.java

/**
 * Main service method for ShoppingServlet
 *
 * @param req Object that encapsulates the request to the servlet
 * @param resp Object that encapsulates the response from the servlet
 *///ww w  .ja  v a  2  s .  c o m
public void performTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action = null;
    action = req.getParameter(Util.ATTR_ACTION);
    Util.debug("action=" + action);
    if (action.equals(ACTION_SHOPPING)) {
        String category = (String) req.getParameter("category");
        HttpSession session = req.getSession(true);
        // Get session category if none on request, such as
        // 'Continue Shopping' from the Shopping Cart jsp.
        if ((category == null) || (category.equals("null"))) {
            category = (String) session.getAttribute(Util.ATTR_CATEGORY);
        }
        // If categoyr still null, default to first category.
        if ((category == null) || (category.equals("null"))) {
            category = "0";
        }
        session.setAttribute(Util.ATTR_CATEGORY, category);
        // Get the shopping items from the catalog.
        Collection c = catalog.getItemsByCategory(Integer.parseInt(category));
        ArrayList items = new ArrayList(c);
        for (int i = 0; i < items.size();) {
            if (((Inventory) items.get(i)).isPublic())
                i++;
            else
                items.remove(i);
        }
        req.setAttribute(Util.ATTR_INVITEMS, items);
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_SHOPPING);
    } else if (action.equals(ACTION_PRODUCTDETAIL)) {
        String invID = (String) req.getParameter("itemID");
        req.setAttribute(Util.ATTR_INVITEM, catalog.getItemInventory(invID));
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_PRODUCT);
    } else if (action.equals(ACTION_GOTOCART)) {
        HttpSession session = req.getSession(true);
        // Get shopping cart.
        ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        if (shoppingCart != null) {
            // Make sure ShopingCart reference has not timed out.
            try {
                shoppingCart.getItems();
            }
            // TODO: what exception would be thrown?
            catch (RuntimeException e) {
                Util.debug("gotocart: shopping cart ref must have timed out");
                ShoppingCartContents cartContents = (ShoppingCartContents) session
                        .getAttribute(Util.ATTR_CART_CONTENTS);
                shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
                session.setAttribute(Util.ATTR_CART, shoppingCart);
            }
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_CART);
    } else if (action.equals(ACTION_ADDTOCART)) {
        ShoppingCart shoppingCart = null;
        // Get shopping cart.
        HttpSession session = req.getSession(true);
        shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        if (shoppingCart == null) {
            Util.debug("shopping cart is NULL, must create it");
            shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
            System.out.println(
                    "Items:: " + shoppingCart.getItems() + " Size :: " + shoppingCart.getItems().size());
            shoppingCart.setItems(new ArrayList<ShoppingCartItem>());
        } else {
            // Make sure ShopingCart reference has not timed out.
            try {
                Util.debug("shopping cart is not null, check items, size=" + shoppingCart.getItems().size());
                shoppingCart.getItems();
            }
            // TODO: what exception would be thrown?
            catch (RuntimeException e) {
                // ShoppingCart timed out, so create a new one.
                Util.debug("addtocart: shopping cart ref must have timed out, create a new one");
                ShoppingCartContents cartContents = (ShoppingCartContents) session
                        .getAttribute(Util.ATTR_CART_CONTENTS);
                shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
                if (cartContents != null) {
                    shoppingCart.setCartContents(cartContents);
                }
            }
        }
        // Add item to cart.
        if (shoppingCart != null) {
            String invID = req.getParameter("itemID");

            // Gets detached instance
            Inventory inv = catalog.getItemInventory(invID);
            ShoppingCartItem si = new ShoppingCartItem(inv);
            si.setQuantity(Integer.parseInt(req.getParameter("qty").trim()));
            shoppingCart.addItem(si);
            session.setAttribute(Util.ATTR_CART, shoppingCart);
            session.setAttribute(Util.ATTR_CART_CONTENTS, shoppingCart.getCartContents());
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_CART);
    } else if (action.equals(ACTION_UPDATEQUANTITY)) {
        // Get shopping cart.
        HttpSession session = req.getSession(true);
        ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        // Make sure ShopingCart reference has not timed out.
        try {
            shoppingCart.getItems();
        }
        // TODO: what exception gets thrown?
        catch (RuntimeException e) {
            // ShoppingCart timed out, so create a new one.
            Util.debug("updatequantity: shopping cart ref must have timed out, create a new one");
            ShoppingCartContents cartContents = (ShoppingCartContents) session
                    .getAttribute(Util.ATTR_CART_CONTENTS);
            shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");

            if (cartContents != null) {
                shoppingCart.setCartContents(cartContents);
            }
        }
        // Update item quantity in cart.
        if (shoppingCart != null) {
            try {
                int cnt = 0;
                Collection c = shoppingCart.getItems();
                ArrayList items;

                if (c instanceof ArrayList)
                    items = (ArrayList) c;
                else
                    items = new ArrayList(c);
                ShoppingCartItem si;
                String parm, parmval;
                // Check all quantity values from cart form.
                for (int parmcnt = 0;; parmcnt++) {
                    parm = "itemqty" + String.valueOf(parmcnt);
                    parmval = req.getParameter(parm);
                    // No more quantity fields, so break out.
                    if ((parmval == null) || parmval.equals("null")) {
                        break;
                    } else // Check quantity value of cart item.
                    {
                        int quantity = Integer.parseInt(parmval);
                        // Quantity set to 0, so remove from cart.
                        if (quantity == 0) {
                            items.remove(cnt);
                        } else // Change quantity of cart item.
                        {
                            si = (ShoppingCartItem) items.get(cnt);
                            si.setQuantity(quantity);
                            items.set(cnt, si);
                            cnt++;
                        }
                    }
                }
                // Are items in cart? Yes, set the session attributes.
                if (items.size() > 0) {
                    shoppingCart.setItems(items);
                    session.setAttribute(Util.ATTR_CART, shoppingCart);
                    session.setAttribute(Util.ATTR_CART_CONTENTS, shoppingCart.getCartContents());
                } else // No items in cart, so remove attributes from session.
                {
                    session.removeAttribute(Util.ATTR_CART);
                    session.removeAttribute(Util.ATTR_CART_CONTENTS);
                }
            } catch (Exception e) {
                //  Log the exception but try to continue.
                Util.debug("ShoppingServlet.performAction() -> Exception caught: " + e);
                // This should take us to the error page.
                throw new ServletException(e.getMessage());
            }
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_CART);
    } else if (action.equals(ACTION_INITCHECKOUT)) {
        String url;
        HttpSession session = req.getSession(true);
        CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Util.ATTR_CUSTOMER);
        if (customerInfo == null) {
            req.setAttribute(Util.ATTR_RESULTS, "You must login or register before checking out.");
            session.setAttribute(Util.ATTR_CHECKOUT, new Boolean(true));
            url = Util.PAGE_LOGIN;
        } else {
            url = Util.PAGE_ORDERINFO;
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, url);
    } else if (action.equals(ACTION_ORDERINFODONE)) {
        OrderInfo orderinfo = null;
        ShoppingCart shoppingCart = null;
        HttpSession session = req.getSession(true);
        CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Util.ATTR_CUSTOMER);
        String customerID = customerInfo.getCustomerID();
        shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        // Make sure ShopingCart reference has not timed out.
        try {
            Util.debug("orderinfodone: ShoppingCart timeout? check getItems() method");
            shoppingCart.getItems();
        }
        // TODO: what exception gets thrown?
        catch (RuntimeException e) {
            // ShoppingCart timed out, so create a new one.
            Util.debug("orderinfodone: ShoppingCart ref must have timed out");
            ShoppingCartContents cartContents = (ShoppingCartContents) session
                    .getAttribute(Util.ATTR_CART_CONTENTS);
            if (cartContents != null) {
                shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
                shoppingCart.setCartContents(cartContents);
            } else {
                Util.debug("NoSuchObject Exception!!!");
                Util.debug("Major Problem!!!");
                shoppingCart = null;
            }
        }
        Util.debug("orderinfodone: got cart?");
        if (shoppingCart != null) {
            Util.debug("orderinfodone: cart not NULL");
            String billName = req.getParameter("bname");
            String billAddr1 = req.getParameter("baddr1");
            String billAddr2 = req.getParameter("baddr2");
            String billCity = req.getParameter("bcity");
            String billState = req.getParameter("bstate");
            String billZip = req.getParameter("bzip");
            String billPhone = req.getParameter("bphone");
            String shipName = req.getParameter("sname");
            String shipAddr1 = req.getParameter("saddr1");
            String shipAddr2 = req.getParameter("saddr2");
            String shipCity = req.getParameter("scity");
            String shipState = req.getParameter("sstate");
            String shipZip = req.getParameter("szip");
            String shipPhone = req.getParameter("sphone");
            int shippingMethod = Integer.parseInt(req.getParameter("shippingMethod"));
            String creditCard = req.getParameter("ccardname");
            String ccNum = req.getParameter("ccardnum");
            String ccExpireMonth = req.getParameter("ccexpiresmonth");
            String ccExpireYear = req.getParameter("ccexpiresyear");
            String cardHolder = req.getParameter("ccholdername");
            orderinfo = shoppingCart.createOrder(customerID, billName, billAddr1, billAddr2, billCity,
                    billState, billZip, billPhone, shipName, shipAddr1, shipAddr2, shipCity, shipState, shipZip,
                    shipPhone, creditCard, ccNum, ccExpireMonth, ccExpireYear, cardHolder, shippingMethod,
                    shoppingCart.getItems());
            Util.debug("orderinfodone: order created");
        }
        if (orderinfo != null) {
            req.setAttribute(Util.ATTR_ORDERINFO, orderinfo);
            req.setAttribute(Util.ATTR_CARTITEMS, shoppingCart.getItems());
            session.setAttribute(Util.ATTR_ORDERKEY, orderinfo.getID());
            requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_CHECKOUTFINAL);
        }
    } else if (action.equals(ACTION_COMPLETECHECKOUT)) {
        ShoppingCart shoppingCart = null;
        HttpSession session = req.getSession(true);
        long key = (Long) session.getAttribute(Util.ATTR_ORDERKEY);
        req.setAttribute(Util.ATTR_ORDERID, key);
        long orderKey = key;
        Util.debug("completecheckout: order id =" + orderKey);
        CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Util.ATTR_CUSTOMER);
        // Check the available inventory and backorder if necessary.
        shoppingCart = (ShoppingCart) session.getAttribute(Util.ATTR_CART);
        // Make sure ShopingCart reference has not timed out.
        try {
            Util.debug("completecheckout: ShoppingCart timeout? check getItems() method");
            shoppingCart.getItems();
        }
        // TODO: what exception gets thrown?
        catch (RuntimeException e) {
            // ShoppingCart timed out, so create a new one.
            Util.debug("completecheckout: ShoppingCart ref must have timed out");
            ShoppingCartContents cartContents = (ShoppingCartContents) session
                    .getAttribute(Util.ATTR_CART_CONTENTS);
            if (cartContents != null) {
                shoppingCart = (ShoppingCart) WebUtil.getSpringBean(this.getServletContext(), "shopping");
                shoppingCart.setCartContents(cartContents);
            } else {
                Util.debug("NoSuchObject Exception!!!");
                Util.debug("Major Problem!!!");
                shoppingCart = null;
            }
        }
        if (shoppingCart != null) {
            ShoppingCartItem si;
            Collection items = shoppingCart.getItems();
            for (Object o : items) {
                si = (ShoppingCartItem) o;
                shoppingCart.checkInventory(si);
                Util.debug(
                        "ShoppingCart.checkInventory() - checking Inventory quantity of item: " + si.getID());
            }
        }

        try {
            mailer.createAndSendMail(customerInfo, orderKey);
        } catch (MailerAppException e) {
            System.out.println("MailerAppException:" + e);
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("Exception during create and send mail :" + e);
            e.printStackTrace();
        }
        // Remove items saved in HttpSession.
        session.removeAttribute(Util.ATTR_CART);
        session.removeAttribute(Util.ATTR_CART_CONTENTS);
        session.removeAttribute(Util.ATTR_CATEGORY);
        session.removeAttribute(Util.ATTR_ORDERKEY);
        session.removeAttribute(Util.ATTR_CHECKOUT);
        HttpSession httpSession = req.getSession(true);

        //httpSession.invalidate();
        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_ORDERDONE);
    }
}

From source file:com.ibm.replication.iidr.warehouse.CollectCDCStats.java

/**
 * Removes the invalid metric IDs from the list
 * /*from www  . j a  v a 2 s .  c  o m*/
 * @param resultMessage
 *            Error message containing the invalid metrics
 * @param metricIDList
 *            Metric ID list to be adjusted
 * @return Adjusted metric ID list
 */
private ArrayList<String> removeInvalidMetrics(String resultMessage, ArrayList<String> metricIDList) {
    ArrayList<String> returnMetricIDList = new ArrayList<String>(metricIDList);
    Matcher metricsMatcher = Pattern.compile("\\d+(,\\d+)*").matcher(resultMessage);
    if (metricsMatcher.find()) {
        String metrics[] = metricsMatcher.group(0).split(",");
        for (String metricID : metrics) {
            logger.debug("Removing metric ID " + metricID + " from the list");
            returnMetricIDList.remove(metricID);
        }
    }
    return returnMetricIDList;
}

From source file:com.l2jfrozen.gameserver.geo.pathfinding.PathFinding.java

public final Node[] searchByClosest2(final Node start, final Node end) {
    // Always continues checking from the closest to target non-blocked
    // node from to_visit list. There's extra length in path if needed
    // to go backwards/sideways but when moving generally forwards, this is extra fast
    // and accurate. And can reach insane distances (try it with 800 nodes..).
    // Minimum required node count would be around 300-400.
    // Generally returns a bit (only a bit) more intelligent looking routes than
    // the basic version. Not a true distance image (which would increase CPU
    // load) level of intelligence though.

    // List of Visited Nodes
    final L2FastSet<Node> visited = L2Collections.newL2FastSet();
    // List of Nodes to Visit
    final ArrayList<Node> to_visit = L2Collections.newArrayList();
    to_visit.add(start);/*  ww  w. ja va  2  s .  co m*/
    try {
        final int targetx = end.getNodeX();
        final int targety = end.getNodeY();
        int dx, dy;
        boolean added;
        int i = 0;
        while (i < 550) {
            if (to_visit.isEmpty()) {
                // No Path found
                return null;
            }

            final Node node = to_visit.remove(0);

            if (node.equals(end)) // path found!
            {
                return constructPath2(node);
            }
            i++;
            visited.add(node);
            node.attachNeighbors();
            final Node[] neighbors = node.getNeighbors();
            if (neighbors == null)
                continue;
            for (final Node n : neighbors) {
                if (!visited.contains(n) && !to_visit.contains(n)) {
                    added = false;
                    n.setParent(node);
                    dx = targetx - n.getNodeX();
                    dy = targety - n.getNodeY();
                    n.setCost(dx * dx + dy * dy);
                    for (int index = 0; index < to_visit.size(); index++) {
                        // supposed to find it quite early..
                        if (to_visit.get(index).getCost() > n.getCost()) {
                            to_visit.add(index, n);
                            added = true;
                            break;
                        }
                    }
                    if (!added)
                        to_visit.add(n);
                }
            }
        }
        // No Path found
        return null;
    } finally {
        L2Collections.recycle(visited);
        L2Collections.recycle(to_visit);
    }
}

From source file:com.concursive.connect.web.modules.members.portlets.InviteMembersPortlet.java

private void checkDuplicates(LinkedHashMap<String, String> members, String member, String userId) {
    Iterator<String> memIterator = members.keySet().iterator();
    while (memIterator.hasNext()) {
        String keyName = memIterator.next();
        String idValue = members.get(keyName);

        //check only previous values and not entire list
        if (keyName.equals(member)) {
            return;
        }//  w w  w. j a v  a2 s.  c  o  m

        //check if valid ids
        if (NO_MATCH_FOUND.equals(idValue) || !StringUtils.hasText(idValue)) {
            continue;
        }

        //convert comma separated string to ArrayList and remove duplicates
        ArrayList<String> lstIds = new ArrayList<String>(Arrays.asList(idValue.split(",")));
        while (lstIds.contains(userId)) {
            lstIds.remove(userId);
        }

        //convert the id list to comma separated string and assign it to members list if there ids remaining
        if (!lstIds.isEmpty()) {
            String ids = lstIds.toString();
            ids = ids.replace("[", "");
            ids = ids.replace("]", "");
            ids = ids.replace(" ", "");
            members.put(keyName, ids);
        } else {
            memIterator.remove();
        }
    }
}

From source file:com.tesora.dve.sql.util.StorageGroupDDL.java

@Override
public List<String> getCreateStatements() throws Exception {
    ArrayList<String> buf = new ArrayList<String>();
    if (isCreated())
        return buf;
    ArrayList<String> siteNames = new ArrayList<String>();
    for (int i = 0; i < nsites; i++) {
        String sname = siteKern + i;
        siteNames.add(sname);/*from   w  w  w.  j a  va 2  s . com*/
        // create all the sites up front
        buf.add("create persistent site " + sname + " url='"
                + TestCatalogHelper.getInstance().getCatalogBaseUrl() + "' user='"
                + TestCatalogHelper.getInstance().getCatalogUser() + "' password='"
                + TestCatalogHelper.getInstance().getCatalogPassword() + "'");
    }
    if (holdBack > 0 && siteNames.size() > holdBack) {
        // we're going to hold back the trailing sites
        int lim = siteNames.size() - holdBack;
        while (siteNames.size() > lim)
            siteNames.remove(siteNames.size() - 1);
    }
    buf.add("create persistent group " + name + " add " + Functional.join(siteNames, ","));
    setCreated();
    return buf;
}