Example usage for java.util ArrayList isEmpty

List of usage examples for java.util ArrayList isEmpty

Introduction

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

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:eu.tango.energymodeller.datastore.DataGatherer.java

/**
 * This method gathers and writes host measurements to disk and to the
 * background database for future usage.
 *
 * @param host The host to gather data for
 * @param measurement The measurement data to write to disk.
 * @param vmList The list of VMs that are currently running
 *//*from   ww w  .  jav  a  2s.co  m*/
private void gatherMeasurements(Host host, HostMeasurement measurement, double hostOffset,
        List<VmDeployed> vmList) {
    if (lastTimeStampSeen.get(host) == null || measurement.getClock() > lastTimeStampSeen.get(host)) {
        lastTimeStampSeen.put(host, measurement.getClock());
        Logger.getLogger(DataGatherer.class.getName()).log(Level.FINE,
                "Data gatherer: Writing out host information");
        double power = measurement.getPower(true);
        if (power == -1) {
            return; //This guards against not having a Watt meter attached.                    
        }
        double energy = 0;
        if (measurement.getEnergyMetricExist()) {
            energy = measurement.getEnergy();
        }
        database.writeHostHistoricData(host, measurement.getClock(), power, energy);
        if (datasource instanceof TangoEnvironmentDataSourceAdaptor) {
            /**
            * The next line writes host power values. This helps demonstrate where 
            * the application's power consumption derives from.
            */
            ((TangoEnvironmentDataSourceAdaptor) datasource).writeOutHostValuesToInflux(host,
                    measurement.getPower(true));
        }
        if (datasource instanceof CollectDInfluxDbDataSourceAdaptor) {
            /**
            * The next line writes host power values. This helps demonstrate where 
            * the application's power consumption derives from.
            */
            ((CollectDInfluxDbDataSourceAdaptor) datasource).writeOutHostValuesToInflux(host,
                    measurement.getPower(true));
        }
        Logger.getLogger(DataGatherer.class.getName()).log(Level.FINE,
                "Data gatherer: Obtaining list of vms on host {0}", host.getHostName());
        ArrayList<VmDeployed> vms = getVMsOnHost(host, vmList);
        if (!vms.isEmpty()) {
            HostEnergyUserLoadFraction fraction = new HostEnergyUserLoadFraction(host, measurement.getClock());
            Logger.getLogger(DataGatherer.class.getName()).log(Level.FINE,
                    "Data gatherer: Obtaining specific vm information");
            List<VmMeasurement> vmMeasurements = datasource.getVmData(vms);
            if (useWorkloadCache) {
                workloadCache.addVMToStatistics(vmMeasurements);
            }
            fraction.setFraction(vmMeasurements);
            fraction.setHostPowerOffset(hostOffset);
            Logger.getLogger(DataGatherer.class.getName()).log(Level.FINE,
                    "Data gatherer: Writing out vm information");
            database.writeHostVMHistoricData(host, measurement.getClock(), fraction);
            if (vmUsageLogger != null) {
                Logger.getLogger(DataGatherer.class.getName()).log(Level.FINE,
                        "Data gatherer: Logging out to Zabbix file");
                vmUsageLogger.printToFile(vmUsageLogger.new Pair(measurement, fraction));
            }
        }
        List<ApplicationOnHost> apps = datasource.getHostApplicationList(ApplicationOnHost.JOB_STATUS.RUNNING);
        apps = ApplicationOnHost.filter(apps, host);
        if (!apps.isEmpty() && datasource instanceof ApplicationDataSource) {
            Logger.getLogger(DataGatherer.class.getName()).log(Level.FINE,
                    "Data gatherer: Obtaining specific app information");
            List<ApplicationMeasurement> appMeasurements = ((ApplicationDataSource) datasource)
                    .getApplicationData(apps);
            HostEnergyUserLoadFraction fraction = new HostEnergyUserLoadFraction(host, measurement.getClock());
            fraction.setApplicationFraction(appMeasurements);
            fraction.setHostPowerOffset(hostOffset);
            //TODO Write this data to the database
            if (appUsageLogger != null) {
                Logger.getLogger(DataGatherer.class.getName()).log(Level.FINE,
                        "Data gatherer: Logging out to Zabbix file, for applications");
                appUsageLogger.printToFile(appUsageLogger.new Pair(measurement, fraction));
            }
        }
    }
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplTest.java

/**
 * Test method for {@link net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl#getCertificate(java.lang.String, java.lang.String)}.
 * @throws CMException //from  w w  w  . ja  v  a  2  s . c om
 */
@Test
public void testGetCertificate() throws CMException {
    String alias = credentialManager.addKeyPair(privateKey, privateKeyCertChain);
    // Get certificate from the Keystore associated with the private key we just inserted
    Certificate privateKeyCertificate = credentialManager
            .getCertificate(CredentialManager.KeystoreType.KEYSTORE, alias);
    assertNotNull(privateKeyCertificate);
    assertTrue(privateKeyCertChain[0].equals(privateKeyCertificate));

    // We should also have some trusted certificates in the Truststore
    // Need to get their aliases
    ArrayList<String> truststoreAliases = credentialManager
            .getAliases(CredentialManager.KeystoreType.TRUSTSTORE);
    assertTrue(!truststoreAliases.isEmpty());
    // Just get the first one
    Certificate trustedCertificate = credentialManager.getCertificate(CredentialManager.KeystoreType.TRUSTSTORE,
            truststoreAliases.get(0));
    assertNotNull(trustedCertificate);
}

From source file:it.eng.spagobi.profiling.dao.SbiUserDAOHibImpl.java

public ArrayList<UserBO> loadUsers() throws EMFUserError {
    logger.debug("IN");
    ArrayList<UserBO> users = null;
    Session aSession = null;/*from w  w w  .j ava  2 s.  c o m*/
    Transaction tx = null;
    try {
        aSession = getSession();
        tx = aSession.beginTransaction();
        Criteria crit = aSession.createCriteria(SbiUser.class);

        ArrayList<SbiUser> result = (ArrayList<SbiUser>) crit.list();
        if (result != null && !result.isEmpty()) {
            users = new ArrayList<UserBO>();
            for (int i = 0; i < result.size(); i++) {
                users.add(toUserBO(result.get(i)));
            }
        }

        return users;
    } catch (HibernateException he) {
        logger.error(he.getMessage(), he);
        if (tx != null)
            tx.rollback();
        throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
    } finally {
        logger.debug("OUT");
        if (aSession != null) {
            if (aSession.isOpen())
                aSession.close();
        }
    }
}

From source file:com.google.dart.engine.internal.element.ClassElementImpl.java

@Override
public boolean hasNonFinalField() {
    ArrayList<ClassElement> classesToVisit = new ArrayList<ClassElement>();
    HashSet<ClassElement> visitedClasses = new HashSet<ClassElement>();
    classesToVisit.add(this);
    while (!classesToVisit.isEmpty()) {
        ClassElement currentElement = classesToVisit.remove(0);
        if (visitedClasses.add(currentElement)) {
            // check fields
            for (FieldElement field : currentElement.getFields()) {
                if (!field.isFinal() && !field.isConst() && !field.isStatic() && !field.isSynthetic()) {
                    return true;
                }/*from   w ww . java 2s. co  m*/
            }
            // check mixins
            for (InterfaceType mixinType : currentElement.getMixins()) {
                ClassElement mixinElement = mixinType.getElement();
                classesToVisit.add(mixinElement);
            }
            // check super
            InterfaceType supertype = currentElement.getSupertype();
            if (supertype != null) {
                ClassElement superElement = supertype.getElement();
                if (superElement != null) {
                    classesToVisit.add(superElement);
                }
            }
        }
    }
    // not found
    return false;
}

From source file:com.zimbra.common.util.QuotedTextUtil.java

/**
 * Removes quoted content from identified blocks of text by analyzing the
 * content we have classified//  w  w w  .  jav  a2 s .  c  om
 *
 * @param text the message content
 * @param results the list of {@link Fragment}
 * @param unknownBlock list of remaining unknown blocks
 * @param count a map that maintains a count of line types
 * @return String containing only original message and not the quoted content
 */
private String removeQuotedText(String text, ArrayList<Fragment> results, ArrayList<String> unknownBlock,
        Map<LineType, Integer> count) {
    Fragment firstFragment = null;
    Fragment secondFragment = null;
    if (!results.isEmpty()) {
        firstFragment = results.get(0);
        if (results.size() > 1) {
            secondFragment = results.get(1);
        }
    }

    //empty content followed by HEADER
    if ((firstFragment != null && (firstFragment.getType() == LineType.HEADER
            || firstFragment.getType() == LineType.WROTE_STRONG))) {
        return "";
    }

    // Check for UNKNOWN followed by HEADER
    if ((firstFragment != null && firstFragment.getType() == LineType.UNKNOWN)
            && (secondFragment != null && (secondFragment.getType() == LineType.HEADER
                    || secondFragment.getType() == LineType.WROTE_STRONG))) {
        String originalText = getTextFromBlock(firstFragment.getBlock());
        if (originalText != null) {
            return originalText;
        }
    }

    // check for special case of WROTE preceded by UNKNOWN, followed by mix
    // of UNKNOWN and QUOTED (inline reply)
    String originalText = checkInlineWrote(count, results, false);
    if (originalText != null) {
        return originalText;
    }

    // If we found quoted content and there's exactly one UNKNOWN block,
    // return it.
    if (getCount(count, LineType.UNKNOWN) == 1 && getCount(count, LineType.QUOTED) > 0) {
        originalText = getTextFromBlock(unknownBlock);
        if (originalText != null) {
            return originalText;
        }
    }

    // If we have a STRONG separator (eg "--- Original Message ---"),
    // consider it authoritative and return the text that precedes it
    if (getCount(count, LineType.SEP_STRONG) > 0) {
        ArrayList<String> block = new ArrayList<String>();
        for (Fragment resFragment : results) {
            if (resFragment.getType() == LineType.SEP_STRONG) {
                break;
            }
            block.addAll(resFragment.getBlock());
        }
        originalText = getTextFromBlock(block);
        if (originalText != null) {
            return originalText;
        }
    }

    return text;
}

From source file:com.google.dart.engine.internal.element.ClassElementImpl.java

private void collectAllSupertypes(ArrayList<InterfaceType> supertypes) {
    ArrayList<InterfaceType> typesToVisit = new ArrayList<InterfaceType>();
    ArrayList<ClassElement> visitedClasses = new ArrayList<ClassElement>();
    typesToVisit.add(this.getType());
    while (!typesToVisit.isEmpty()) {
        InterfaceType currentType = typesToVisit.remove(0);
        ClassElement currentElement = currentType.getElement();
        if (!visitedClasses.contains(currentElement)) {
            visitedClasses.add(currentElement);
            if (currentType != this.getType()) {
                supertypes.add(currentType);
            }/*w  ww .j  a  v a 2  s  .  c o  m*/
            InterfaceType supertype = currentType.getSuperclass();
            if (supertype != null) {
                typesToVisit.add(supertype);
            }
            for (InterfaceType type : currentElement.getInterfaces()) {
                typesToVisit.add(type);
            }
            for (InterfaceType type : currentElement.getMixins()) {
                ClassElement element = type.getElement();
                if (!visitedClasses.contains(element)) {
                    supertypes.add(type);
                }
            }
        }
    }
}

From source file:com.ga.forms.DailyLogAddUI.java

private void initComponentValues() {
    args = new HashMap();
    dateObj = new Date();
    formatDateToday = new SimpleDateFormat("dd-MMM-yyyy");
    dateDisplayLbl.setText(formatDateToday.format(dateObj));
    args.put("date", formatDateToday.format(dateObj));
    DailyLogRecord record = new DailyLogRecord();
    ArrayList logRecord = record.retrieveRecord(args);
    formatDateToday = new SimpleDateFormat("EEEE", Locale.ENGLISH);
    dayDisplayLbl.setText(formatDateToday.format(dateObj));
    timeList = new ArrayList<String>();
    timeList = getTimeList();//www .  ja v  a 2  s .  c  om
    if (!logRecord.isEmpty()) {
        args.clear();
        args = new HashMap();
        formatDateToday = new SimpleDateFormat("HH:mm");
        currentTime = formatDateToday.format(dateObj);
        DailyLogAddUI.logRecordJSONObject = new JSONObject((Map) logRecord.get(0));
        DailyLogAddUI.logRecordMetaJSONObject = new JSONObject(
                (Map) DailyLogAddUI.logRecordJSONObject.get("meta"));
        DailyLogAddUI.checkIn = Boolean
                .parseBoolean((String) DailyLogAddUI.logRecordMetaJSONObject.get("checked-in"));
        if (DailyLogAddUI.logRecordMetaJSONObject.get("had-break").equals("")
                || DailyLogAddUI.logRecordMetaJSONObject.get("had-break").equals("false")) {
            DailyLogAddUI.breakDone = false;
        } else {
            DailyLogAddUI.breakDone = Boolean
                    .parseBoolean((String) DailyLogAddUI.logRecordMetaJSONObject.get("had-break"));
        }
        checkInTimeCombo.setModel(new DefaultComboBoxModel(timeList.toArray()));
        checkInTimeCombo.setSelectedIndex(timeList.indexOf(DailyLogAddUI.logRecordJSONObject.get("check-in")));
        checkInTimeCombo.setEnabled(false);
        if (!DailyLogAddUI.breakDone) {
            breakOptionPanel.setEnabled(true);
            yesRdButton.setEnabled(true);
            noRdButton.setEnabled(true);
            customRdButton.setEnabled(true);
            checkInOutButton.setText("Update");

        } else {
            breakOptionPanel.setEnabled(false);
            yesRdButton.setEnabled(false);
            noRdButton.setEnabled(false);
            customRdButton.setEnabled(false);
            this.timeOnBreak = DailyLogAddUI.logRecordJSONObject.get("break").toString();
            checkInOutButton.setPreferredSize(new Dimension(115, 29));
            checkInOutButton.setText("Check Out");

        }
        DailyLogDuration durationAgent = new DailyLogDuration();
        durationAgent.calculateCurrentDuration(DailyLogAddUI.logRecordJSONObject.get("check-in").toString(),
                this.timeOnBreak, "");
        String currentTimeDuration = durationAgent.getCurrentDuration();
        String[] currentTimeDurationArray = currentTimeDuration.split(":");
        int hours = Integer.parseInt(currentTimeDurationArray[0]);
        if (hours >= 9 && (DailyLogAddUI.logRecordMetaJSONObject.get("checked-out").equals("")
                || DailyLogAddUI.logRecordMetaJSONObject.get("checked-out").equals("false"))) { // or duration <=9 and duration>=7
            DailyLogAddUI.checkOut = false;
        } else {
            DailyLogAddUI.checkOut = Boolean
                    .parseBoolean((String) DailyLogAddUI.logRecordMetaJSONObject.get("checked-out"));
        }
        if (!DailyLogAddUI.checkOut) {
            checkOutTimeCombo.setModel(new DefaultComboBoxModel(timeList.toArray()));
            checkOutTimeCombo.setSelectedIndex(timeList.indexOf(currentTime));

        } else {
            checkOutTimeCombo.setModel(new DefaultComboBoxModel(timeList.toArray()));
            checkOutTimeCombo
                    .setSelectedIndex(timeList.indexOf(DailyLogAddUI.logRecordJSONObject.get("check-out")));
            checkOutTimeCombo.setEnabled(false);
            checkInOutButton.setEnabled(false);
        }

    } else {
        formatDateToday = new SimpleDateFormat("HH:mm");
        currentTime = formatDateToday.format(dateObj);
        checkInTimeCombo.setModel(new DefaultComboBoxModel(timeList.toArray()));
        checkInTimeCombo.setSelectedIndex(timeList.indexOf(currentTime));
        checkOutTimeCombo.setModel(new DefaultComboBoxModel(timeList.toArray()));
        checkOutTimeCombo.setSelectedIndex(timeList.indexOf("00:00"));
    }
    groupRadioButtons();
}

From source file:ti.modules.titanium.network.NetworkModule.java

/**
 * Gets all the cookies with the domain matched with the given value.
 * @param domain the domain of the cookie to get. It is case-insensitive.
 * @return an array of cookies with the domain matched.
 *///from  w  w  w  .  j ava 2  s.co  m
@Kroll.method
public CookieProxy[] getHTTPCookiesForDomain(String domain) {
    if (domain == null || domain.length() == 0) {
        if (Log.isDebugModeEnabled()) {
            Log.e(TAG, "Unable to get the HTTP cookies. Need to provide a valid domain.");
        }
        return null;
    }
    ArrayList<CookieProxy> cookieList = new ArrayList<CookieProxy>();
    List<Cookie> cookies = getHTTPCookieStoreInstance().getCookies();
    for (Cookie cookie : cookies) {
        String cookieDomain = cookie.getDomain();
        if (domainMatch(cookieDomain, domain)) {
            cookieList.add(new CookieProxy(cookie));
        }
    }
    if (!cookieList.isEmpty()) {
        return cookieList.toArray(new CookieProxy[cookieList.size()]);
    }
    return null;
}

From source file:knowledgeMiner.mining.SentenceParserHeuristic.java

/**
 * Pairs the nouns and adjectives together to produce a number of result
 * text fragments to be resolved to concepts.
 *
 * @param parse/* w w  w.ja v  a 2 s .  co  m*/
 *            The parse to process and pair.
 * @param anchors
 *            The anchor map.
 * @param existingAnchorTrees
 *            The anchor trees already added to the results (for reuse and
 *            subtree-ing)
 * @return A collection of possible mappable entities composed of at least
 *         one noun and possible adjectives (with sub-adjectives).
 */
private Collection<Tree<String>> pairNounAdjs(Parse parse, SortedMap<String, String> anchors,
        Map<String, Tree<String>> existingAnchorTrees) {
    Collection<Tree<String>> results = new ArrayList<>();
    boolean createNewNounSet = false;
    ArrayList<String> nounPhrases = new ArrayList<>();
    Parse[] children = parse.getChildren();
    for (int i = children.length - 1; i >= 0; i--) {
        String childType = children[i].getType();
        String childText = children[i].getCoveredText();
        if (childType.startsWith("NN") || childType.equals("NP")) {
            // Note the noun, adding it to the front of the existing NP.
            if (createNewNounSet)
                nounPhrases.clear();
            String existingNounPhrase = "";
            if (!nounPhrases.isEmpty())
                existingNounPhrase = nounPhrases.get(nounPhrases.size() - 1);
            String np = (childText + " " + existingNounPhrase).trim();
            nounPhrases.add(np);

            // Add to the tree (if not a pure anchor)
            if (!anchors.containsKey(np))
                results.add(new Tree<String>(reAnchorString(np, anchors)));
        } else if (childType.startsWith("JJ") || childType.equals("ADJP")) {
            // Only process if we have an NP
            if (!nounPhrases.isEmpty()) {
                // For every nounPhrase
                StringBuilder adjective = new StringBuilder();
                for (int j = i; children[j].getType().startsWith("JJ")
                        || children[j].getType().equals("ADJP"); j++) {
                    // Build adjective combinations
                    if (adjective.length() != 0)
                        adjective.append(" ");
                    adjective.append(children[j].getCoveredText());
                    for (String np : nounPhrases) {
                        // Create the tree (with sub adjective tree)
                        String adjNP = adjective + " " + np;
                        Tree<String> adjP = null;
                        // Check for an existing anchor tree
                        if (existingAnchorTrees.containsKey(adjNP))
                            adjP = existingAnchorTrees.get(adjNP);
                        else
                            adjP = new Tree<String>(reAnchorString(adjNP, anchors));
                        if (!anchors.containsKey(adjective.toString()))
                            adjP.addSubValue(reAnchorString(adjective.toString(), anchors));

                        // Add to the tree
                        results.add(adjP);
                    }
                }
            }
            createNewNounSet = true;
        } else {
            createNewNounSet = true;
        }
    }
    return results;
}

From source file:com.l2jfree.gameserver.instancemanager.AutoChatManager.java

private void restoreChatData() {
    int numLoaded = 0;
    Connection con = null;/*from   www .  jav a 2s.c o  m*/
    PreparedStatement statement = null;
    PreparedStatement statement2 = null;
    ResultSet rs = null;
    ResultSet rs2 = null;

    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);

        statement = con.prepareStatement("SELECT * FROM auto_chat ORDER BY groupId ASC");
        rs = statement.executeQuery();

        while (rs.next()) {
            int groupId = rs.getInt("groupId");
            int npcId = rs.getInt("npcId");
            long chatDelay = rs.getLong("chatDelay") * 1000;
            int chatRange = rs.getInt("chatRange");
            boolean chatRandom = rs.getBoolean("chatRandom");

            numLoaded++;

            statement2 = con.prepareStatement("SELECT * FROM auto_chat_text WHERE groupId=?");
            statement2.setInt(1, groupId);
            rs2 = statement2.executeQuery();

            ArrayList<String> chatTexts = new ArrayList<String>();

            while (rs2.next())
                chatTexts.add(rs2.getString("chatText"));

            if (!chatTexts.isEmpty())
                registerGlobalChat(npcId, chatTexts.toArray(new String[chatTexts.size()]), chatDelay, chatRange,
                        chatRandom);
            else
                _log.warn("AutoChatHandler: Chat group " + groupId + " is empty.");

            statement2.close();
        }

        statement.close();

        if (_log.isDebugEnabled())
            _log.info("AutoChatHandler: Loaded " + numLoaded + " chat group(s) from the database.");
    } catch (Exception e) {
        _log.warn("AutoSpawnHandler: Could not restore chat data: ", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}