Example usage for java.util ArrayList toString

List of usage examples for java.util ArrayList toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:de.ub0r.android.websms.connector.o2.ConnectorO2.java

/**
 * Load captcha and wait for user input to solve it.
 * /*from w  w  w.  ja v  a2s .com*/
 * @param context
 *            {@link Context}
 * @param flow
 *            _flowExecutionKey
 * @return true if captcha was solved
 * @throws IOException
 *             IOException
 */
private boolean solveCaptcha(final Context context, final String flow) throws IOException {
    HttpResponse response = Utils.getHttpClient(URL_CAPTCHA, null, null, TARGET_AGENT, URL_LOGIN, ENCODING,
            O2_SSL_FINGERPRINTS);
    int resp = response.getStatusLine().getStatusCode();
    if (resp != HttpURLConnection.HTTP_OK) {
        throw new WebSMSException(context, R.string.error_http, "" + resp);
    }
    BitmapDrawable captcha = new BitmapDrawable(response.getEntity().getContent());
    final Intent intent = new Intent(Connector.ACTION_CAPTCHA_REQUEST);
    intent.putExtra(Connector.EXTRA_CAPTCHA_DRAWABLE, captcha.getBitmap());
    captcha = null;
    this.getSpec(context).setToIntent(intent);
    context.sendBroadcast(intent);
    try {
        synchronized (CAPTCHA_SYNC) {
            CAPTCHA_SYNC.wait(CAPTCHA_TIMEOUT);
        }
    } catch (InterruptedException e) {
        Log.e(TAG, null, e);
        return false;
    }
    if (captchaSolve == null) {
        return false;
    }
    // got user response, try to solve captcha
    Log.d(TAG, "got solved captcha: " + captchaSolve);
    final ArrayList<BasicNameValuePair> postData = // .
            new ArrayList<BasicNameValuePair>(3);
    postData.add(new BasicNameValuePair("_flowExecutionKey", flow));
    postData.add(new BasicNameValuePair("_eventId", "submit"));
    postData.add(new BasicNameValuePair("riddleValue", captchaSolve));
    response = Utils.getHttpClient(URL_SOLVECAPTCHA, null, postData, TARGET_AGENT, URL_LOGIN, ENCODING,
            O2_SSL_FINGERPRINTS);
    Log.d(TAG, postData.toString());
    resp = response.getStatusLine().getStatusCode();
    if (resp != HttpURLConnection.HTTP_OK) {
        throw new WebSMSException(context, R.string.error_http, "" + resp);
    }
    final String mHtmlText = Utils.stream2str(response.getEntity().getContent());
    if (mHtmlText.indexOf(CHECK_WRONGCAPTCHA) > 0) {
        throw new WebSMSException(context, R.string.error_wrongcaptcha);
    }
    return true;
}

From source file:UserInterface.AdminWorkArea.InventoryUsageJPanel.java

public void findTopDevice() {

    int max = 0;//  ww w .  j a  v  a2  s .  c  om
    int current = 0;
    String currentPName = "null";
    ArrayList<String> currentPList = new ArrayList<>();
    currentPList.add("null");
    DefaultTableModel dtm = (DefaultTableModel) deviceUsageJTable.getModel();

    for (int i = 0; i < dtm.getRowCount(); i++) {
        current = (int) dtm.getValueAt(i, 1);
        if (max < current) {
            max = current;
            IDeviceType dt = (IDeviceType) dtm.getValueAt(i, 0);
            currentPName = dt.getTypeOfDevice();
            currentPList.clear();
            currentPList.add(currentPName);
        } else if (max == current) {
            IDeviceType dt = (IDeviceType) dtm.getValueAt(i, 0);
            currentPName = dt.getTypeOfDevice();
            currentPList.add(currentPName);
        }
    }
    mostUsedLabel.setText(currentPList.toString());
}

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;
        }/*from  w  w  w  .  j av  a 2 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:UserInterface.AdminWorkArea.InventoryUsageJPanel.java

public void findLeastUsedDevices() {
    int min = 0;//from w w w .  j av  a2 s .  com
    int current = 0;
    String currentPName = "null";
    ArrayList<String> currentPList = new ArrayList<>();
    currentPList.add("null");
    DefaultTableModel dtm = (DefaultTableModel) deviceUsageJTable.getModel();
    min = (int) dtm.getValueAt(0, 1);
    for (int i = 0; i < dtm.getRowCount(); i++) {
        current = (int) dtm.getValueAt(i, 1);
        if (min > current) {
            min = current;
            IDeviceType dt = (IDeviceType) dtm.getValueAt(i, 0);
            currentPName = dt.getTypeOfDevice();
            currentPList.clear();
            currentPList.add(currentPName);
        } else if (min == current) {
            IDeviceType dt = (IDeviceType) dtm.getValueAt(i, 0);
            currentPName = dt.getTypeOfDevice();
            currentPList.add(currentPName);
        }
    }
    leastUsedLabel.setText(currentPList.toString());
}

From source file:web.AddauthorController.java

/**
 * This method is called by the spring framework. The configuration
 * for this controller to be invoked is based on the pagetype and
 * is set in the urlMapping property in the spring config file.
 *
 * @param request the <code>HttpServletRequest</code>
 * @param response the <code>HttpServletResponse</code>
 * @throws ServletException/*from   w ww. ja v a2s  . com*/
 * @throws IOException
 * @return ModelAndView this instance is returned to spring
 */
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // ***************************************************************************
    // This will initialize common data in the abstract class and the return result is of no value.
    // The abstract class initializes protected variables, login, collabrum, logininfo.
    // Which can be accessed in all controllers if they want to.
    // ***************************************************************************

    try {
        ModelAndView m = super.handleRequest(request, response);
    } catch (Exception e) {
        return handleError("error in handleRequest", e);
    }

    if (!WebUtil.isLicenseProfessional(login)) {
        return handleError("Cannot manage AddAuthors() feature in deluxe version.");
    }

    // ***************************************************************************
    // This is the only line of code you need to get all session info initialized!
    // Always be the first line before anything else is done. Add to each controller's
    // handlRequest method. Also recollabrum to extend SessionObject.
    // ***************************************************************************
    outOfSession(request, response);

    if (RegexStrUtil.isNull(login) || (loginInfo == null)) {
        return handleUserpageError("Login/loginInfo is null in AddauthorController.");
    }

    boolean checkall = false;
    if ((!RegexStrUtil.isNull(request.getParameter(DbConstants.CHECKALL)))
            && (request.getParameter(DbConstants.CHECKALL).equalsIgnoreCase("on"))) {
        checkall = true;
    }

    String alphabet = request.getParameter(DbConstants.ALPHABET);
    if (RegexStrUtil.isNull(alphabet)) {
        alphabet = "A";
    }

    String directoryId = request.getParameter(DbConstants.DIRECTORY_ID);
    String size = request.getParameter(DbConstants.SIZE);
    if (RegexStrUtil.isNull(size)) {
        return handleError("list size is null, AddauthorController for login " + login);
    }
    logger.info("size = " + size);

    if (!RegexStrUtil.isNull(directoryId)) {
        if (directoryId.length() > GlobalConst.directoryidSize) {
            return handleError("directoryId.length() > WebConstants.directoryIdSize AddauthorController ");
        }
        directoryId = RegexStrUtil.goodNameStr(directoryId);
    } else {
        return handleError("directoryId is null, AddauthorController ");
    }

    /**
     *  adds members as authors for this directory
     */
    DirectoryAuthorDao authorDao = (DirectoryAuthorDao) daoMapper.getDao(DbConstants.DIRECTORY_AUTHOR);
    if ((authorDao == null)) {
        return handleError("DirectoryAuthorDao is null in AddauthorController collabrum, " + login);
    }

    DirectoryDao dirDao = (DirectoryDao) daoMapper.getDao(DbConstants.DIRECTORY);
    if ((dirDao == null)) {
        return handleError("dirDao is null in AddauthorController collabrum, " + login);
    }

    int colListSize = new Integer(size).intValue();
    ArrayList idList = new ArrayList();
    String myString = null;
    String val = "";

    if (checkall) {
        for (int i = 0; i < colListSize; i++) {
            val = new Integer(i).toString();
            myString = "col" + val;
            idList.add(request.getParameter(myString));
        }
    } else {
        for (int i = 0; i < colListSize; i++) {
            val = new Integer(i).toString();
            if ((!RegexStrUtil.isNull(request.getParameter(val)))
                    && (request.getParameter(val).equalsIgnoreCase("on"))) {
                myString = "col" + val;
                idList.add(request.getParameter(myString));
            }
        }
    }

    logger.info("idList = " + idList.toString() + ", size=" + idList.size());

    /**
     *  lists the authors of this directory 
     */
    HashSet authorSet = null;
    List users = null;
    HashSet alphabetUsers = null;
    Directory directory = null;
    try {
        if (loginInfo != null) {
            String userId = loginInfo.getValue(DbConstants.LOGIN_ID);
            authorDao.addAuthors(directoryId, userId, login, idList);
            if (checkall) {
                users = authorDao.getAllUsersAlphabet(directoryId, userId, login, DbConstants.READ_FROM_SLAVE);
                alphabetUsers = authorDao.getAlphabetSet(users);
            } else {
                users = authorDao.getUsers(alphabet, directoryId, userId, login, DbConstants.READ_FROM_SLAVE);
            }
            authorSet = authorDao.listAuthorsOfDirectory(directoryId, userId, login,
                    DbConstants.READ_FROM_MASTER);
            directory = dirDao.viewDirectory(directoryId, userId, login, DbConstants.READ_FROM_SLAVE,
                    DbConstants.BLOB_READ_FROM_SLAVE, DbConstants.WEBSITE_READ_FROM_SLAVE);
        }
    } catch (BaseDaoException e) {
        return handleError(
                "Exception occured, listAuthorsOfDirectory()/viewDirectory()/getUsers/getAllUsersAlphabet()  AddauthorController for login "
                        + login + " ErrorMsg=" + e.getMessage(),
                e);
    }

    if (authorSet == null) {
        return handleError("authorSet, AddauthorController login " + login);
    }

    CobrandDao cobrandDao = (CobrandDao) getDaoMapper().getDao(DbConstants.COBRAND);
    if (cobrandDao == null) {
        return handleUserpageError("CobrandDao is null, AddauthorController");
    }
    Userpage cobrand = cobrandDao.getUserCobrand(loginInfo.getValue(DbConstants.LOGIN_ID));

    //if (!WebUtil.isLdapActive()) {
    String viewName = DbConstants.SHOW_USERS;
    Map myModel = new HashMap();
    if (checkall) {
        myModel.put(DbConstants.HIGHLIGHT, "all");
        viewName = DbConstants.SHOW_ALL_USERS_DIR;
    } else {
        viewName = DbConstants.SHOW_USERS;
        myModel.put(DbConstants.HIGHLIGHT, alphabet);
    }
    myModel.put(DbConstants.LOGIN_INFO, loginInfo);
    myModel.put(DbConstants.USERS_ALPHABET, alphabetUsers);
    myModel.put(DbConstants.MEMBERS, authorSet);
    myModel.put(DbConstants.USERS, users);
    myModel.put(DbConstants.COBRAND, cobrand);
    myModel.put(DbConstants.DIRECTORY, directory);
    myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
    myModel.put(DbConstants.USER_PAGE, userpage);
    if (DiaryAdmin.isDiaryAdmin(login)) {
        myModel.put(DbConstants.BUSINESS_EXISTS, "1");
    } else {
        myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
    }
    return new ModelAndView(viewName, "model", myModel);
    //}
}

From source file:ruige.GrabFTPDateManager.java

private static void handleFileAndInsertDB(String tempPath, String savePath, String fromType, String errorPath)
        throws Exception {
    String filepath = tempPath.substring(0, tempPath.length() - 1);
    File file = new File(filepath);
    ArrayList<String> errorList = new ArrayList<String>();
    if (file.isDirectory()) {//
        String[] filelist = file.list();
        for (int i = 0; i < filelist.length; i++) {
            File readfile = new File(filepath + "\\" + filelist[i]);
            long len = 0;
            if (len == readfile.length()) { //
                continue;
            }/*from   w w  w  . j  a v  a2s  .  com*/
            if (!readfile.isDirectory()) {
                String filename = readfile.getName();
                if (filename.contains("DEC") || filename.contains("RCP")) {
                    Boolean isMoveSuccess = readfile.renameTo(new File(errorPath + filename));
                    if (isMoveSuccess) {
                        readfile.delete();
                    }
                } else {
                    //xml
                    Boolean isInsertSuccess = insertIntoDB(tempPath, filename, fromType);
                    if (isInsertSuccess) {
                        //
                        Boolean isMoveSuccess = readfile.renameTo(new File(savePath + filename));
                        if (isMoveSuccess) {
                            readfile.delete();
                        }
                    } else {
                        errorList.add(filename);
                    }
                }
            }
        }
        if (null != errorList && errorList.size() > 0) {
            GlobalFunc.sendEmail("lijw@regs.com", "",
                    "" + errorList.toString(), 0);
        }
    }
}

From source file:eu.vital.vitalcep.restApp.filteringApi.StaticFiltering.java

/**
 * Creates a filter.//from   ww  w .  jav  a  2  s . c om
 *
 * @param info
 * @return the filter id 
 * @throws java.io.IOException 
 */
@POST
@Path("filterstaticdata")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response filterstaticdata(String info, @Context HttpServletRequest req)
        throws IOException, UnsupportedEncodingException, NoSuchAlgorithmException {

    JSONObject jo = new JSONObject(info);

    if (jo.has("dolceSpecification") && jo.has("data")) { // && jo.has("data") for demo

        MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL));
        MongoDatabase db = mongo.getDatabase(mongoDB);

        try {
            db.getCollection("staticdatafilters");
        } catch (Exception e) {
            //System.out.println("Mongo is down");
            db = null;
            if (mongo != null) {
                mongo.close();
                mongo = null;
            }
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();

        }

        if (jo.has("dolceSpecification")) {

            //Filter oFilter = new Filter(filter);
            JSONObject dsjo = jo.getJSONObject("dolceSpecification");
            String str = dsjo.toString();//"{\"dolceSpecification\": "+ dsjo.toString()+"}";

            try {

                DolceSpecification ds = new DolceSpecification(str);

                if (!(ds instanceof DolceSpecification)) {
                    return Response.status(Response.Status.BAD_REQUEST).build();
                }

                String mqin = RandomStringUtils.randomAlphanumeric(8);
                String mqout = RandomStringUtils.randomAlphanumeric(8);

                JSONArray aData = jo.getJSONArray("data");

                CEP cepProcess = new CEP();

                if (!(cepProcess.CEPStart(CEP.CEPType.DATA, ds, mqin, mqout, confFile, aData.toString(),
                        null))) {
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
                }

                String clientName = "collector_" + RandomStringUtils.randomAlphanumeric(4);

                if (cepProcess.PID < 1) {
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
                }

                UUID uuid = UUID.randomUUID();
                String randomUUIDString = uuid.toString();

                DBObject dbObject = createCEPFilterStaticSensorJsonld(info, randomUUIDString, jo, dsjo,
                        "vital:CEPFilterStaticDataSensor");
                Document doc = new Document(dbObject.toMap());

                try {
                    db.getCollection("staticdatafilters").insertOne(doc);
                    String id = doc.get("_id").toString();

                } catch (MongoException ex) {
                    db = null;
                    if (mongo != null) {
                        mongo.close();
                        mongo = null;
                    }
                    return Response.status(Response.Status.BAD_REQUEST).build();
                }

                JSONObject opState = createOperationalStateObservation(randomUUIDString);

                DBObject oPut = (DBObject) JSON.parse(opState.toString());
                Document doc1 = new Document(oPut.toMap());

                try {
                    db.getCollection("staticdatafiltersobservations").insertOne(doc1);
                    String id = doc1.get("_id").toString();

                } catch (MongoException ex) {
                    db = null;
                    if (mongo != null) {
                        mongo.close();
                        mongo = null;
                    }
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
                }

                /////////////////////////////////////////////////////
                // creates client and messages process
                //
                MqttAllInOne oMqtt = new MqttAllInOne();
                TMessageProc MsgProcc = new TMessageProc();

                /////////////////////////////////////////////////////////////////////////
                // PREPARING DOLCE INPUT
                Decoder decoder = new Decoder();
                ArrayList<String> simpleEventAL = decoder.JsonldArray2DolceInput(aData);

                String sal = simpleEventAL.toString();
                /////////////////////////////////////////////////////////////////////////////
                // SENDING TO MOSQUITTO
                oMqtt.sendMsg(MsgProcc, clientName, simpleEventAL, mqin, mqout, false);

                /////////////////////////////////////////////////////////////////////////////
                //RECEIVING FROM MOSQUITO               
                ArrayList<MqttMsg> mesagges = MsgProcc.getMsgs();

                ArrayList<Document> outputL;
                outputL = new ArrayList<>();

                Encoder encoder = new Encoder();

                outputL = encoder.dolceOutputList2ListDBObject(mesagges, host, randomUUIDString);

                String sOutput = "[";
                for (int i = 0; i < outputL.size(); i++) {
                    Document element = outputL.get(i);

                    if (i == 0) {
                        sOutput = sOutput + element.toJson();
                    }
                    sOutput = sOutput + "," + element.toJson();
                }

                sOutput = sOutput + "]";

                StringBuilder ck = new StringBuilder();

                try {
                    Security slogin = new Security();

                    Boolean token = slogin.login(req.getHeader("name"), req.getHeader("password"), false, ck);
                    if (!token) {
                        return Response.status(Response.Status.UNAUTHORIZED).build();
                    }
                    cookie = ck.toString();

                    DMSManager oDMS = new DMSManager(dmsURL, cookie);

                    MongoCollection<Document> collection = db.getCollection("staticdatafiltersobservations");

                    if (outputL.size() > 0) {
                        collection.insertMany(outputL);
                        if (!oDMS.pushObservations(sOutput)) {
                            java.util.logging.Logger.getLogger(StaticFiltering.class.getName())
                                    .log(Level.SEVERE, "couldn't save to the DMS");
                        }
                    }

                } catch (KeyManagementException | KeyStoreException ex) {
                    db = null;
                    if (mongo != null) {
                        mongo.close();
                        mongo = null;
                    }
                    java.util.logging.Logger.getLogger(MessageProcessor_publisher.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
                //cepProcess.
                try {
                    CepContainer.deleteCepProcess(cepProcess.PID);

                    if (!cepProcess.cepDispose()) {
                        java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE,
                                "couldn't terminate ucep");
                    }
                } catch (Exception e) {
                    java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE, null,
                            e);
                }
                db = null;
                if (mongo != null) {
                    mongo.close();
                    mongo = null;
                }
                return Response.status(Response.Status.OK).entity(sOutput).build();

            } catch (IOException | JSONException | java.text.ParseException e) {
                db = null;
                if (mongo != null) {
                    mongo.close();
                    mongo = null;
                }
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
            }
        }

        return Response.status(Response.Status.BAD_REQUEST).build();

    }

    return Response.status(Response.Status.BAD_REQUEST).build();

}

From source file:ru.kaefik.isaifutdinov.an_weather_widget.city.CityModel.java

public ArrayList<String> getLikeNameCity(String searchNameCity) {
    Log.i(ConfigActivity.TAG_SERVICE, " CityModel getLikeNameCity -> start ");
    String url = "http://api.openweathermap.org/data/2.5/find?q=" + searchNameCity + "&type=like&APPID="
            + getMYAPPID();//from  ww  w  . j  a v  a 2 s . c o m
    ArrayList<String> result = new ArrayList<String>();
    String res = Utils.getHttpRequestFromUrl(url);

    Gson gson = new Gson();
    if (res == null) {
        // TODO:      
        System.out.println("   ");
    } else {
        Log.i(ConfigActivity.TAG_SERVICE, " CityModel getLikeNameCity -> res " + res);
        ArrayCityModel cc = gson.fromJson(res, ArrayCityModel.class);
        System.out.println(cc.getCount());
        for (int i = 0; i < cc.getCount(); i++) {
            result.add(cc.list[i].getName());
        }
    }
    Log.i(ConfigActivity.TAG_SERVICE, " CityModel getLikeNameCity ->  " + result.toString());
    return result;
}

From source file:at.fhooe.mcm.saap.facebook.HelloFacebookSampleActivity.java

private String buildUserInfoDisplay(GraphUser user) {
    StringBuilder userInfo = new StringBuilder("");

    // Example: typed access (name)
    // - no special permissions required
    userInfo.append(String.format("Name: %s\n\n", user.getName()));

    // Example: typed access (birthday)
    // - requires user_birthday permission
    userInfo.append(String.format("Birthday: %s\n\n", user.getBirthday()));

    // Example: partially typed access, to location field,
    // name key (location)
    // - requires user_location permission
    userInfo.append(String.format("Location: %s\n\n", user.getLocation().getProperty("name")));

    // Example: access via property name (locale)
    // - no special permissions required
    userInfo.append(String.format("Locale: %s\n\n", user.getProperty("locale")));

    // Example: access via property name (locale)
    // - no special permissions required
    if (user.getProperty("sports") != null) {
        userInfo.append(String.format("favorite_teams: %s\n\n", user.getProperty("sports")));
    }//from w w w.j  ava2s  .c o m
    // Example: access via property name (locale)
    // - no special permissions required
    if (user.getProperty("favorite_teams") != null) {
        userInfo.append(String.format("favorite_teams: %s\n\n", user.getProperty("favorite_teams")));
    }
    if (user.getProperty("favorite_athletes") != null) {
        userInfo.append(String.format("favorite_athletes: %s\n\n", user.getProperty("favorite_athletes")));
    }

    // Example: access via key for array (languages)
    // - requires user_likes permission
    JSONArray languages = (JSONArray) user.getProperty("languages");
    if (languages != null) {
        if (languages.length() > 0) {
            ArrayList<String> languageNames = new ArrayList<String>();
            for (int i = 0; i < languages.length(); i++) {
                JSONObject language = languages.optJSONObject(i);
                // Add the language name to a list. Use JSON
                // methods to get access to the name field.
                languageNames.add(language.optString("name"));
            }
            userInfo.append(String.format("Languages: %s\n\n", languageNames.toString()));
        }
    }

    return userInfo.toString();
}

From source file:org.apache.stratos.cloud.controller.iaases.openstack.networking.NeutronNetworkingApi.java

/**
 * Assign a {@link FloatingIP} from the given {@link FloatingNetwork} to the given {@link Port}.
 * It will either assign an existing floating IP
 * or it will create and assign a new floating IP.
 *
 * @param port                the {@link Port} to which a floating IP to be assigned.
 * @param floatingNetworkUuid the network uuid of the floating network
 *                            from which a floating IP to be chosen/created
 * @return the assigned Floating IP/*from  ww  w .  j  av  a2  s . c  o m*/
 */
private FloatingIP assignFloatingIP(Port port, String floatingNetworkUuid) {
    // checking whether if there are any available floating IPs in the external network
    // if there are any we don't need to create a new one
    ArrayList<FloatingIP> unassignedFloatingIPs = getUnassignedFloatingIPsByNetworkUuid(floatingNetworkUuid);

    // we should remove all predefined floating IPs from unassigned list
    // otherwise, these predefined floating IPs can be associated to some other interfaces
    if (unassignedFloatingIPs != null) {
        if (log.isDebugEnabled()) {
            String msg = String.format("Unassigned floating IPs from the network %s - %s", floatingNetworkUuid,
                    unassignedFloatingIPs.toString());
            log.debug(msg);
        }
        Iterator<FloatingIP> unassginedFloatingIPsIterator = unassignedFloatingIPs.iterator();
        while (unassginedFloatingIPsIterator.hasNext()) {
            FloatingIP floatingIP = unassginedFloatingIPsIterator.next();
            List<String> allPredefinedFloatingIPs = getAllPredefinedFloatingIPs(
                    iaasProvider.getNetworkInterfaces());
            if (allPredefinedFloatingIPs != null && !allPredefinedFloatingIPs.isEmpty()) {
                if (log.isDebugEnabled()) {
                    String msg = String.format("Predefined  floating IPs - %s found in cartridge",
                            allPredefinedFloatingIPs.toString());
                    log.debug(msg);
                }
                Iterator<String> predefinedFloatingIPsIterator = allPredefinedFloatingIPs.iterator();
                while (predefinedFloatingIPsIterator.hasNext()) {
                    String floatingIPAddress = predefinedFloatingIPsIterator.next();
                    if (floatingIP.getFloatingIpAddress() != null
                            && floatingIP.getFloatingIpAddress().equals(floatingIPAddress)) {
                        unassginedFloatingIPsIterator.remove();
                        if (log.isDebugEnabled()) {
                            String msg = String.format(
                                    "Removed predefined floating IP %s from available floating IPs",
                                    floatingIPAddress);
                            log.debug(msg);
                        }
                    }
                }
            }
        }
    }

    if (unassignedFloatingIPs == null || unassignedFloatingIPs.isEmpty()) {
        return createAndAssignFloatingIP(port, floatingNetworkUuid);
    }

    if (log.isDebugEnabled()) {
        String msg = String.format("Available floating IPs from the network %s - %s", floatingNetworkUuid,
                unassignedFloatingIPs.toString());
        log.debug(msg);
    }

    // shuffle and get the last for randomness
    Collections.shuffle(unassignedFloatingIPs);
    FloatingIP selectedFloatingIP = Iterables.getLast(unassignedFloatingIPs);

    if (log.isDebugEnabled()) {
        String msg = String.format("Floating IP %s is selected among %s from the network %s",
                selectedFloatingIP.getFloatingIpAddress(), unassignedFloatingIPs.toString(),
                floatingNetworkUuid);
        log.debug(msg);
    }

    return updateFloatingIP(selectedFloatingIP, port);
}