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:com.foxykeep.datadroid.internal.network.NetworkConnectionImpl.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result./*from   w  w w .  j av  a 2s .co  m*/
 *
 * @param context The context to use for this operation. Used to generate the user agent if
 *            needed.
 * @param urlValue The webservice URL.
 * @param method The request method to use.
 * @param parameterList The parameters to add to the request.
 * @param headerMap The headers to add to the request.
 * @param isGzipEnabled Whether the request will use gzip compression if available on the
 *            server.
 * @param userAgent The user agent to set in the request. If null, a default Android one will be
 *            created.
 * @param postText The POSTDATA text to add in the request.
 * @param credentials The credentials to use for authentication.
 * @param isSslValidationEnabled Whether the request will validate the SSL certificates.
 * @return The result of the webservice call.
 */
public static ConnectionResult execute(Context context, String urlValue, Method method,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled) throws ConnectionException {
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // Log the request
        if (DataDroidLog.canLog(Log.DEBUG)) {
            DataDroidLog.d(TAG, "Request url: " + urlValue);
            DataDroidLog.d(TAG, "Method: " + method.toString());

            if (parameterList != null && !parameterList.isEmpty()) {
                DataDroidLog.d(TAG, "Parameters:");
                for (int i = 0, size = parameterList.size(); i < size; i++) {
                    BasicNameValuePair parameter = parameterList.get(i);
                    String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                    DataDroidLog.d(TAG, message);
                }

                DataDroidLog.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

            if (postText != null) {
                DataDroidLog.d(TAG, "Post data: " + postText);
            }

            if (headerMap != null && !headerMap.isEmpty()) {
                DataDroidLog.d(TAG, "Headers:");
                for (Entry<String, String> header : headerMap.entrySet()) {
                    DataDroidLog.d(TAG, "- " + header.getKey() + " = " + header.getValue());
                }
            }
        }

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = postText;
            }
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(OPERATION_TIMEOUT);

        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT) && outputText != null) {
            OutputStream output = null;
            try {
                output = connection.getOutputStream();
                output.write(outputText.getBytes());
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing to do here.
                    }
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        DataDroidLog.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            String error = convertStreamToString(errorStream, isGzip);
            throw new ConnectionException(error, responseCode);
        }

        String body = convertStreamToString(connection.getInputStream(), isGzip);

        if (DataDroidLog.canLog(Log.VERBOSE)) {
            DataDroidLog.v(TAG, "Response body: ");

            int pos = 0;
            int bodyLength = body.length();
            while (pos < bodyLength) {
                DataDroidLog.v(TAG, body.substring(pos, Math.min(bodyLength - 1, pos + 200)));
                pos = pos + 200;
            }
        }

        return new ConnectionResult(connection.getHeaderFields(), body);
    } catch (IOException e) {
        DataDroidLog.e(TAG, "IOException", e);
        throw new ConnectionException(e);
    } catch (KeyManagementException e) {
        DataDroidLog.e(TAG, "KeyManagementException", e);
        throw new ConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        DataDroidLog.e(TAG, "NoSuchAlgorithmException", e);
        throw new ConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:UserInterface.PatientRole.ManageMyVitalSignsAndFitnessRecordJPanel.java

private void showVitalSignsChartJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showVitalSignsChartJButtonActionPerformed
    // TODO add your handling code here:
    ArrayList<Record> recordList = patient.getRecordHistory().getRecordList();
    /*At least 2 vital sign records needed to show chart */
    if (recordList.isEmpty() || recordList.size() == 1) {
        JOptionPane.showMessageDialog(this,
                "No Vital Signs or only one Vital Sign found. At least 2 Vital Signs records needed to show chart!",
                "Warning", JOptionPane.INFORMATION_MESSAGE);
        return;/*from  w w  w  .j a v  a  2s  .c  o  m*/
    }
    VitalSignsChartJPanel panel = new VitalSignsChartJPanel(userProcessContainer, userAccount,
            patientOrganization, enterprise, ecoSystem);
    userProcessContainer.add("VitalSignsChartJPanel", panel);
    CardLayout layout = (CardLayout) userProcessContainer.getLayout();
    layout.next(userProcessContainer);
}

From source file:com.norconex.collector.core.data.store.impl.mongo.MongoCrawlDataStore.java

private void processedToCached() {
    BasicDBObject whereQuery = new BasicDBObject(IMongoSerializer.FIELD_STAGE, Stage.PROCESSED.name());
    whereQuery.put(IMongoSerializer.FIELD_IS_VALID, true);
    DBCursor cursor = collRefs.find(whereQuery);

    // Add them to cache in batch
    ArrayList<DBObject> list = new ArrayList<DBObject>(BATCH_UPDATE_SIZE);
    while (cursor.hasNext()) {
        list.add(cursor.next());/*from   w  w  w  .  j  av  a 2  s . c o m*/
        if (list.size() == BATCH_UPDATE_SIZE) {
            collCached.insert(list);
            list.clear();
        }
    }
    if (!list.isEmpty()) {
        collCached.insert(list);
    }
}

From source file:dk.cafeanalog.AnalogDownloader.java

public List<DayOfOpenings> getDaysOfOpenings() throws JSONException, ParseException, IOException {
    ArrayList<Opening> openings = getOpenings();

    Collections.sort(openings, new Comparator<Opening>() {
        @Override/*from   w  w  w. j  av a 2  s.c o m*/
        public int compare(Opening lhs, Opening rhs) {
            return lhs.getOpen().compareTo(rhs.getOpen());
        }
    });

    ArrayList<DayOfOpenings> result = new ArrayList<>();

    Calendar calendar = Calendar.getInstance();

    for (Opening opening : openings) {
        calendar.setTime(opening.getOpen());
        int dayOfMonth = calendar.get(Calendar.DATE);
        DayOfOpenings day;
        boolean retrieved = false;
        if (!result.isEmpty()) {
            day = result.get(result.size() - 1);
            if (day.getDayOfMonth() != dayOfMonth) {
                day = new DayOfOpenings(dayOfMonth, calendar.get(Calendar.DAY_OF_WEEK));
            } else {
                retrieved = true;
            }
        } else {
            day = new DayOfOpenings(dayOfMonth, calendar.get(Calendar.DAY_OF_WEEK));
        }

        int openHour = calendar.get(Calendar.HOUR_OF_DAY);
        switch (openHour) {
        case 9:
            day.setMorning();
            break;
        case 11:
            day.setNoon();
            break;
        case 14:
            day.setAfternoon();
            break;
        default:
            Log.d("OpeningsTranslation", "Wrong hour: " + openHour);
        }
        calendar.setTime(opening.getClose());

        int closeHour = calendar.get(Calendar.HOUR_OF_DAY);

        if (openHour == 9 && closeHour == 14) {
            day.setNoon();
        } else if (openHour == 9 && closeHour == 17) {
            day.setNoon();
            day.setAfternoon();
        } else if (openHour == 11 && closeHour == 17) {
            day.setAfternoon();
        }

        if (!retrieved)
            result.add(day);
    }

    return result;
}

From source file:applab.search.client.JsonSimpleParser.java

private void deleteOldMenus() {
    ArrayList<String> localMenuIds = storage.getLocalMenuIds();

    // Check if local menu ids match the new ones; if local id doesn't exist
    // among new ids delete it and all its children
    if (!localMenuIds.isEmpty()) {
        for (int i = 0; i < menuIdsCollection.size(); i++) {
            if (!menuIdsCollection.contains(localMenuIds.get(i))) {
                storage.deleteMenuEntry(localMenuIds.get(i));
                storage.deleteMenuItemEntry(localMenuIds.get(i));
                deletedNodes++;//from  w  w  w .  j  a  v a 2  s. c o m
            }
        }
    }
}

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

/**
 * Take page design and build portlet list in memory only, preferences cannot
 * be saved on these portlets/*  w  ww  . j  a v a2 s.com*/
 *
 * @param page
 * @throws Exception
 */
public void buildTemporaryList(DashboardPage page) throws Exception {
    XMLUtils xml = new XMLUtils(page.getXmlDesign());
    // Counter for number of instances on this page
    int falseIdCount = 0;
    // Pages have rows
    ArrayList rows = new ArrayList();
    XMLUtils.getAllChildren(xml.getDocumentElement(), "row", rows);
    // ERROR if no rows found
    if (rows.isEmpty()) {
        LOG.error("buildTemporaryList-> rows is empty");
    }
    Iterator i = rows.iterator();
    while (i.hasNext()) {
        Element rowEl = (Element) i.next();
        // Rows have columns
        ArrayList columns = new ArrayList();
        XMLUtils.getAllChildren(rowEl, "column", columns);
        // ERROR if no columns found
        if (columns.isEmpty()) {
            LOG.error("buildTemporaryList-> columns is empty");
        }
        Iterator j = columns.iterator();
        while (j.hasNext()) {
            Element columnEl = (Element) j.next();
            // Columns have portlets
            ArrayList portlets = new ArrayList();
            XMLUtils.getAllChildren(columnEl, "portlet", portlets);
            Iterator k = portlets.iterator();
            while (k.hasNext()) {
                Element portletEl = (Element) k.next();
                // Give the portlet an instance reference
                ++falseIdCount;
                // Set the portlet information
                DashboardPortlet portlet = new DashboardPortlet();
                portlet.setPageId(page.getId());
                portlet.setName(portletEl.getAttribute("name"));
                if (portletEl.hasAttribute("viewer")) {
                    portlet.setViewer(portletEl.getAttribute("viewer"));
                }
                if (portletEl.hasAttribute("class")) {
                    portlet.setHtmlClass(portletEl.getAttribute("class"));
                }
                if (portletEl.hasAttribute("cache")) {
                    portlet.setCacheTime(Integer.parseInt(portletEl.getAttribute("cache")));
                }
                if (portletEl.hasAttribute("timeout")) {
                    portlet.setTimeout(Integer.parseInt(portletEl.getAttribute("timeout")));
                }
                if (portletEl.hasAttribute("isSensitive")) {
                    portlet.setSensitive(portletEl.getAttribute("isSensitive"));
                }
                // This portlet can temporarily be used
                DashboardPortletItem portletItem = new DashboardPortletItem();
                portletItem.setName(portlet.getName());
                portletItem.setEnabled(true);
                // Portlets could have default preferences specified in the layout
                ArrayList<Element> preferences = new ArrayList<Element>();
                XMLUtils.getAllChildren(portletEl, preferences);
                Iterator l = preferences.iterator();
                while (l.hasNext()) {
                    Element preferenceEl = (Element) l.next();
                    if ("portlet-events".equals(preferenceEl.getNodeName())) {
                        // This is the registration of a generateDataEvent
                        ArrayList<Element> generateDataEvents = new ArrayList<Element>();
                        XMLUtils.getAllChildren(preferenceEl, "generates-data", generateDataEvents);
                        for (Element gde : generateDataEvents) {
                            portlet.addGenerateDataEvent(XMLUtils.getNodeText(gde));
                        }
                        // This is the registration of a consumeDataEvent
                        ArrayList<Element> consumeDataEvents = new ArrayList<Element>();
                        XMLUtils.getAllChildren(preferenceEl, "consumes-data", consumeDataEvents);
                        for (Element cde : consumeDataEvents) {
                            portlet.addConsumeDataEvent(XMLUtils.getNodeText(cde));
                        }
                        // This is the registration of generateSessionData
                        ArrayList<Element> generateSessionData = new ArrayList<Element>();
                        XMLUtils.getAllChildren(preferenceEl, "generates-session-data", generateSessionData);
                        for (Element cde : generateSessionData) {
                            portlet.addGenerateSessionData(XMLUtils.getNodeText(cde));
                        }
                        // This is the registration of consumeSessionData
                        ArrayList<Element> consumeSessionData = new ArrayList<Element>();
                        XMLUtils.getAllChildren(preferenceEl, "consumes-session-data", consumeSessionData);
                        for (Element cde : consumeSessionData) {
                            portlet.addConsumeSessionDataEvent(XMLUtils.getNodeText(cde));
                        }
                        // This is the registration of generateRequestData
                        ArrayList<Element> generateRequestData = new ArrayList<Element>();
                        XMLUtils.getAllChildren(preferenceEl, "generates-request-data", generateRequestData);
                        for (Element cde : generateRequestData) {
                            portlet.addGenerateRequestData(XMLUtils.getNodeText(cde));
                        }
                        // This is the registration of consumeRequestData
                        ArrayList<Element> consumeRequestData = new ArrayList<Element>();
                        XMLUtils.getAllChildren(preferenceEl, "consumes-request-data", consumeRequestData);
                        for (Element cde : consumeRequestData) {
                            portlet.addConsumeRequestDataEvent(XMLUtils.getNodeText(cde));
                        }
                    } else {
                        // Provide the default preference
                        DashboardPortletPrefs prefs = new DashboardPortletPrefs();
                        prefs.setName(preferenceEl.getNodeName());
                        // Check to see if the prefs are provided as an array
                        ArrayList<String> valueList = new ArrayList<String>();
                        ArrayList valueElements = new ArrayList();
                        XMLUtils.getAllChildren(preferenceEl, "value", valueElements);
                        if (valueElements.size() > 0) {
                            // There are <value> nodes
                            Iterator vi = valueElements.iterator();
                            while (vi.hasNext()) {
                                valueList.add(XMLUtils.getNodeText((Element) vi.next()));
                            }
                            prefs.setValues(valueList.toArray(new String[valueList.size()]));
                        } else {
                            // There is a single value
                            prefs.setValues(new String[] { XMLUtils.getNodeText(preferenceEl) });
                        }
                        portlet.addDefaultPreference(prefs.getName(), prefs);
                    }
                }
                portlet.setId(falseIdCount);
                this.add(portlet);
            }
        }
    }
}

From source file:UserInterface.PatientRole.ManageMyVitalSignsAndFitnessRecordJPanel.java

private void createChart() {
    DefaultCategoryDataset vitalSignDataset = new DefaultCategoryDataset();
    int selectedRow = viewVitalSignsJTable1.getSelectedRow();
    ArrayList<Record> recordList = patient.getRecordHistory().getRecordList();
    /*At least 2 vital sign records needed to show chart */
    if (recordList.isEmpty() || recordList.size() == 1) {
        JOptionPane.showMessageDialog(this,
                "No Fitness Record or only one fitness record found. At least 2 fitness records needed to show chart!",
                "Warning", JOptionPane.INFORMATION_MESSAGE);
        return;/*from w  w  w . j  a v  a  2s  .  c  om*/
    }
    for (Record record : recordList) {
        vitalSignDataset.addValue(record.getStandTime(), "StandTime", record.getDate());
        vitalSignDataset.addValue(record.getMoveTime(), "MoveTime", record.getDate());
        vitalSignDataset.addValue(record.getExcerciseTime(), "ExcerciseTime", record.getDate());
        vitalSignDataset.addValue(record.getTotalTime(), "TotalTime", record.getDate());
    }

    JFreeChart vitalSignChart = ChartFactory.createBarChart3D("Fitness Record Chart", "Time Stamp",
            "Time(mins)", vitalSignDataset, PlotOrientation.VERTICAL, true, false, false);
    vitalSignChart.setBackgroundPaint(Color.white);
    CategoryPlot vitalSignChartPlot = vitalSignChart.getCategoryPlot();
    vitalSignChartPlot.setBackgroundPaint(Color.lightGray);

    CategoryAxis vitalSignDomainAxis = vitalSignChartPlot.getDomainAxis();
    vitalSignDomainAxis
            .setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));

    NumberAxis vitalSignRangeAxis = (NumberAxis) vitalSignChartPlot.getRangeAxis();
    vitalSignRangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    ChartFrame chartFrame = new ChartFrame("Chart", vitalSignChart);
    chartFrame.setVisible(true);
    chartFrame.setSize(500, 500);
}

From source file:main.ScorePipeline.java

/**
 * This method calculates similarities bin-based between yeast_human spectra
 * on the first data set against all yeast spectra on the second data set
 *
 * @param min_mz/*from  ww w  .  j  a  v  a 2 s  . c o m*/
 * @param max_mz
 * @param topN
 * @param percentage
 * @param yeast_and_human_file
 * @param is_precursor_peak_removal
 * @param fragment_tolerance
 * @param noiseFiltering
 * @param transformation
 * @param intensities_sum_or_mean_or_median
 * @param yeast_spectra
 * @param bw
 * @param charge
 * @param charge_situation
 * @throws IllegalArgumentException
 * @throws ClassNotFoundException
 * @throws IOException
 * @throws MzMLUnmarshallerException
 * @throws NumberFormatException
 * @throws ExecutionException
 * @throws InterruptedException
 */
private static void calculate_BinBasedScoresObsolete_AllTogether(ArrayList<BinMSnSpectrum> yeast_spectra,
        ArrayList<BinMSnSpectrum> yeast_human_spectra, BufferedWriter bw, int charge, double precursorTol,
        double fragTol) throws IllegalArgumentException, ClassNotFoundException, IOException,
        MzMLUnmarshallerException, NumberFormatException, InterruptedException {
    ExecutorService excService = Executors
            .newFixedThreadPool(ConfigHolder.getInstance().getInt("thread.numbers"));
    List<Future<SimilarityResult>> futureList = new ArrayList<>();
    for (BinMSnSpectrum binYeastHumanSp : yeast_human_spectra) {
        int tmpMSCharge = binYeastHumanSp.getSpectrum().getPrecursor().getPossibleCharges().get(0).value;
        if (charge == 0 || tmpMSCharge == charge) {
            if (!binYeastHumanSp.getSpectrum().getPeakList().isEmpty() && !yeast_spectra.isEmpty()) {
                Calculate_Similarity similarity = new Calculate_Similarity(binYeastHumanSp, yeast_spectra,
                        fragTol, precursorTol);
                Future future = excService.submit(similarity);
                futureList.add(future);
            }
        }
    }
    for (Future<SimilarityResult> future : futureList) {
        try {
            SimilarityResult get = future.get();
            String tmp_charge = get.getSpectrumChargeAsString(), spectrum = get.getSpectrumName();
            double tmpPrecMZ = get.getSpectrumPrecursorMZ();
            double dot_product = get.getScores().get(SimilarityMethods.NORMALIZED_DOT_PRODUCT_STANDARD),
                    dot_product_skolow = get.getScores().get(SimilarityMethods.NORMALIZED_DOT_PRODUCT_SOKOLOW),
                    pearson = get.getScores().get(SimilarityMethods.PEARSONS_CORRELATION),
                    spearman = get.getScores().get(SimilarityMethods.SPEARMANS_CORRELATION);
            if (dot_product == Double.MIN_VALUE) {
                LOGGER.info("The similarity for the spectrum " + spectrum
                        + " is too small to keep the record, therefore score is not computed.");
                // Means that score has not been calculated!
                //                    bw.write(tmp_Name + "\t" + tmp_charge + "\t" + tmpPrecMZ + "\t");
                //                    bw.write("NA" + "\t" + "NA" + "\t" + "NA" + "\t" + "NA");
            } else {
                bw.write(spectrum + "\t" + tmp_charge + "\t" + tmpPrecMZ + "\t" + get.getSpectrumToCompare()
                        + "\t");
                bw.write(dot_product + "\t" + dot_product_skolow + "\t" + pearson + "\t" + spearman + "\n");
            }
        } catch (InterruptedException | ExecutionException e) {
            LOGGER.error(e);
        }
    }
}

From source file:com.panet.imeta.core.xml.XMLHandler.java

public static String[] getNodeElements(Node node) {
    ArrayList<String> elements = new ArrayList<String>(); // List of String

    NodeList nodeList = node.getChildNodes();
    if (nodeList == null)
        return null;

    for (int i = 0; i < nodeList.getLength(); i++) {
        String nodeName = nodeList.item(i).getNodeName();
        if (elements.indexOf(nodeName) < 0)
            elements.add(nodeName);//w  ww .  j a v a2 s  .c  om
    }

    if (elements.isEmpty())
        return null;

    return elements.toArray(new String[elements.size()]);
}

From source file:feedsplugin.FeedsPlugin.java

private void updateFeedsInternal() {
    synchronized (mFeeds) {
        mFeeds = new ArrayList<SyndFeed>();
    }/*from   w w  w . j a  va 2  s  .co m*/
    Hashtable<SyndFeed, PluginTreeNode> nodes = new Hashtable<SyndFeed, PluginTreeNode>();
    ArrayList<String> feedUrls = mSettings.getFeeds();
    if (!feedUrls.isEmpty()) {

        /* the class loader of the current thread must be manipulated because ROME searches its
         * properties files via Thread.currentThread.getContextClassLoader(). But that is not the
         * classloader used for ROME classes, so we fake it. */
        ClassLoader cl = SyndFeedImpl.class.getClassLoader();
        Thread.currentThread().setContextClassLoader(cl);

        final FeedFetcherCache feedInfoCache = HashMapFeedInfoCache.getInstance();
        final FeedFetcher feedFetcher = new HttpURLFeedFetcher(feedInfoCache);
        feedFetcher.setUserAgent("TV-Browser Feeds Plugin " + FeedsPlugin.getVersion().toString());
        for (String feedUrl : feedUrls) {
            try {
                final SyndFeed feed = feedFetcher.retrieveFeed(new URL(feedUrl));
                synchronized (mFeeds) {
                    mFeeds.add(feed);
                }
                mLog.info("Loaded " + feed.getEntries().size() + " feed entries from " + feedUrl);
            } catch (Exception e) {
                mLog.severe("Problems loading feed " + feedUrl);
                e.printStackTrace();
            }
        }
    }
    mKeywords = new HashMap<String, ArrayList<SyndEntryWithParent>>();
    if (!mFeeds.isEmpty()) {
        synchronized (mFeeds) {
            for (SyndFeed feed : mFeeds) {
                addFeedKeywords(feed);
            }
        }
        getRootNode().clear();
        ArrayList<String> titles = new ArrayList<String>(mFeeds.size());
        final Channel[] channels = devplugin.Plugin.getPluginManager().getSubscribedChannels();
        Date date = Date.getCurrentDate();
        final int maxDays = 7;
        synchronized (mFeeds) {
            Collections.sort(mFeeds, new Comparator<SyndFeed>() {
                public int compare(SyndFeed o1, SyndFeed o2) {
                    return o1.getTitle().compareToIgnoreCase(o2.getTitle());
                }
            });
            for (SyndFeed feed : mFeeds) {
                PluginTreeNode node = getRootNode().addNode(feed.getTitle());
                List<SyndEntryImpl> entries = feed.getEntries();
                titles.add(feed.getTitle());
                AbstractAction[] subActions = new AbstractAction[entries.size()];
                for (int i = 0; i < subActions.length; i++) {
                    final SyndEntryImpl entry = entries.get(i);
                    subActions[i] = new AbstractAction(entry.getTitle()) {
                        public void actionPerformed(ActionEvent e) {
                            showFeedsDialog(new FeedsDialog(getParentFrame(), entry));
                        }
                    };
                }
                ActionMenu menu = new ActionMenu(
                        new ContextMenuAction(mLocalizer.msg("readEntry", "Read entry")), subActions);
                node.addActionMenu(menu);
                nodes.put(feed, node);
            }
            mSettings.setCachedFeedTitles(titles);
            for (int days = 0; days < maxDays; days++) {
                for (Channel channel : channels) {
                    for (Iterator<Program> iter = devplugin.Plugin.getPluginManager().getChannelDayProgram(date,
                            channel); iter.hasNext();) {
                        final Program prog = iter.next();
                        ArrayList<SyndEntryWithParent> matchingEntries = getMatchingEntries(prog.getTitle());
                        if (!matchingEntries.isEmpty()) {
                            HashSet<SyndFeed> feeds = new HashSet<SyndFeed>();
                            for (SyndEntryWithParent entry : matchingEntries) {
                                feeds.add(entry.getFeed());
                            }
                            for (SyndFeed syndFeed : feeds) {
                                nodes.get(syndFeed).addProgramWithoutCheck(prog);
                                prog.validateMarking();
                            }
                        }
                    }
                }
                date = date.addDays(1);
            }
        }
        mRootNode.update();
    }
}