Example usage for org.dom4j Element getTextTrim

List of usage examples for org.dom4j Element getTextTrim

Introduction

In this page you can find the example usage for org.dom4j Element getTextTrim.

Prototype

String getTextTrim();

Source Link

Document

DOCUMENT ME!

Usage

From source file:org.jivesoftware.site.OpenfireVersionChecker.java

License:Open Source License

/**
 * Returns the list of available plugins.
 *
 * @param pluginsPath the path where the .jar files of the plugins are located.
 * @param xmlRequest original XML request sent by the remote openfire server.
 * @param xmlReply XML reply that contains information about available plugins.
 *//*from   w  ww.ja  va  2  s  .c  o  m*/
private static void availablePlugins(String pluginsPath, Element xmlRequest, Element xmlReply)
        throws Exception {
    // Get the locale of the requester
    Locale requesterLocale = Locale.ENGLISH;
    if (xmlRequest != null) {
        Element localElement = xmlRequest.element("locale");
        if (localElement != null) {
            // Set the locale of the requester
            requesterLocale = localeCodeToLocale(localElement.getTextTrim());
        }
    }
    // Get jar files of plugins
    final Collection<PluginManager.Metadata> plugins = PluginManager.getLatestRelease(Paths.get(pluginsPath));

    // Build answer based on available plugins
    for (PluginManager.Metadata plugin : plugins) {
        // Create answer
        Element latestPlugin = xmlReply.addElement("plugin");

        // TODO Get i18n'ed version of the plugin name and description
        latestPlugin.addAttribute("name", plugin.humanReadableName);
        latestPlugin.addAttribute("description", plugin.humanReadableDescription);

        latestPlugin.addAttribute("url", plugin.getDownloadURL());
        latestPlugin.addAttribute("icon", plugin.getIconURL());
        latestPlugin.addAttribute("readme", plugin.getReadmeURL());
        latestPlugin.addAttribute("changelog", plugin.getChangelogURL());
        latestPlugin.addAttribute("latest", plugin.getPluginVersion().replace("-Release-", "."));
        latestPlugin.addAttribute("licenseType", plugin.getLicenceType());
        latestPlugin.addAttribute("author", plugin.getAuthor());
        latestPlugin.addAttribute("minServerVersion", plugin.getMinimumRequiredOpenfireVersion());
        latestPlugin.addAttribute("releaseDate", RELEASE_DATE_FORMAT.format(plugin.releaseDate));

        // Include size of plugin
        latestPlugin.addAttribute("fileSize", Long.toString(plugin.getFileSize()));
    }
}

From source file:org.jivesoftware.site.WildfireVersionChecker.java

License:Open Source License

/**
 * Returns the list of available plugins that are not installed in the Wildfire server.
 * The request contains the plugins that are installed.
 *
 * @param pluginsPath the path where the .jar files of the plugins are located.
 * @param xmlRequest original XML request sent by the remote wildfire server.
 * @param xmlReply XML reply that contains information about available plugins.
 *//*from   ww  w.  j  ava  2  s . c om*/
private static void availablePlugins(String pluginsPath, Element xmlRequest, Element xmlReply)
        throws Exception {
    // Get the locale of the requester
    Locale requesterLocale = Locale.ENGLISH;
    if (xmlRequest != null) {
        Element localElement = xmlRequest.element("locale");
        if (localElement != null) {
            // Set the locale of the requester
            requesterLocale = localeCodeToLocale(localElement.getTextTrim());
        }
    }
    // Get jar files of plugins
    File pluginDir = new File(pluginsPath);
    File[] plugins = pluginDir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar") || name.endsWith(".war");
        }
    });
    // Refresh (if required) information about available plugins
    Collection<String> availablePlugins = getPluginsInfo(plugins).keySet();
    // Build answer based on available plugins
    for (String pluginFilename : availablePlugins) {
        // Get the jar file of the plugin
        File pluginFile = null;
        for (File file : plugins) {
            if (pluginFilename.equals(file.getName())) {
                pluginFile = file;
                break;
            }
        }
        if (pluginFile == null) {
            // Should never happen but if jar file is no longer available then skip this plugin
            continue;
        }
        // Create answer
        Element latestPlugin = xmlReply.addElement("plugin");
        // Get the information specified in plugin.xml
        Document doc = pluginsInfo.get(pluginFilename);

        // Get i18n'ed version of the plugin name and description
        Element n1 = (Element) doc.selectSingleNode("/plugin/name");
        String name = (n1 == null ? pluginFilename
                : geti18nText(pluginFile, n1.getTextTrim(), requesterLocale));
        latestPlugin.addAttribute("name", name);
        n1 = (Element) doc.selectSingleNode("/plugin/description");
        String desc = (n1 == null ? "" : geti18nText(pluginFile, n1.getTextTrim(), requesterLocale));
        latestPlugin.addAttribute("description", desc);

        latestPlugin.addAttribute("url", PLUGINS_PATH + pluginFilename);
        latestPlugin.addAttribute("icon", getIconURL(pluginsPath, pluginFilename));
        latestPlugin.addAttribute("readme", getReadmeURL(pluginsPath, pluginFilename));
        latestPlugin.addAttribute("changelog", getChangelogURL(pluginsPath, pluginFilename));

        Element version = (Element) doc.selectSingleNode("/plugin/version");
        Element licenseType = (Element) doc.selectSingleNode("/plugin/licenseType");
        Element author = (Element) doc.selectSingleNode("/plugin/author");
        Element minVersion = (Element) doc.selectSingleNode("/plugin/minServerVersion");

        latestPlugin.addAttribute("latest", version != null ? version.getTextTrim() : null);
        latestPlugin.addAttribute("licenseType", licenseType != null ? licenseType.getTextTrim() : null);
        latestPlugin.addAttribute("author", author != null ? author.getTextTrim() : null);
        latestPlugin.addAttribute("minServerVersion", minVersion != null ? minVersion.getTextTrim() : null);
        // Include size of plugin
        latestPlugin.addAttribute("fileSize", Long.toString(pluginFile.length()));
    }
}

From source file:org.jivesoftware.util.ElementUtil.java

License:Open Source License

/**
 * Returns the value of the specified property. A <tt>null</tt> answer does not necessarily mean
 * that the property does not exist.//www. jav a 2s.  c  om
 *
 * @param name the name of the property to get.
 * @return the value of the specified property.
 */
public static String getProperty(Element element, String name) {
    String value = null;
    String[] propName = parsePropertyName(name);

    // Grab the attribute if there is one
    String lastName = propName[propName.length - 1];
    String attName = null;
    int attributeIndex = lastName.indexOf(':');
    if (attributeIndex >= 0) {
        propName[propName.length - 1] = lastName.substring(0, attributeIndex);
        attName = lastName.substring(attributeIndex + 1);
    }

    // Search for this property by traversing down the XML hierarchy.
    int i = propName[0].equals(element.getName()) ? 1 : 0;
    for (; i < propName.length; i++) {
        element = element.element(propName[i]);
        if (element == null) {
            break;
        }
    }
    if (element != null) {
        if (attName == null) {
            value = element.getTextTrim();
        } else {
            value = element.attributeValue(attName);
        }
    }

    return value;
}

From source file:org.jivesoftware.util.XMLProperties.java

License:Open Source License

/**
 * Returns the value of the specified property.
 *
 * @param name the name of the property to get.
 * @param ignoreEmpty Ignore empty property values (return null)
 * @return the value of the specified property.
 */// ww w  . j  a v a 2s  .  c  om
public synchronized String getProperty(String name, boolean ignoreEmpty) {
    String value = propertyCache.get(name);
    if (value != null) {
        return value;
    }

    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML hierarchy.
    Element element = document.getRootElement();
    for (String aPropName : propName) {
        element = element.element(aPropName);
        if (element == null) {
            // This node doesn't match this part of the property name which
            // indicates this property doesn't exist so return null.
            return null;
        }
    }
    // At this point, we found a matching property, so return its value.
    // Empty strings are returned as null.
    value = element.getTextTrim();
    if (ignoreEmpty && "".equals(value)) {
        return null;
    } else {
        // check to see if the property is marked as encrypted
        if (JiveGlobals.isPropertyEncrypted(name)) {
            Attribute encrypted = element.attribute(ENCRYPTED_ATTRIBUTE);
            if (encrypted != null) {
                value = JiveGlobals.getPropertyEncryptor().decrypt(value);
            } else {
                // rewrite property as an encrypted value
                Log.info("Rewriting XML property " + name + " as an encrypted value");
                setProperty(name, value);
            }
        }
        // Add to cache so that getting property next time is fast.
        propertyCache.put(name, value);
        return value;
    }
}

From source file:org.jivesoftware.util.XMLProperties.java

License:Open Source License

/**
 * Return all values who's path matches the given property
 * name as a String array, or an empty array if the if there
 * are no children. This allows you to retrieve several values
 * with the same property name. For example, consider the
 * XML file entry://from ww w  . ja  v  a2 s . c  o  m
 * <pre>
 * &lt;foo&gt;
 *     &lt;bar&gt;
 *         &lt;prop&gt;some value&lt;/prop&gt;
 *         &lt;prop&gt;other value&lt;/prop&gt;
 *         &lt;prop&gt;last value&lt;/prop&gt;
 *     &lt;/bar&gt;
 * &lt;/foo&gt;
 * </pre>
 * If you call getProperties("foo.bar.prop") will return a string array containing
 * {"some value", "other value", "last value"}.
 *
 * @param name the name of the property to retrieve
 * @return all child property values for the given node name.
 */
public List<String> getProperties(String name, boolean asList) {
    List<String> result = new ArrayList<String>();
    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML hierarchy,
    // stopping one short.
    Element element = document.getRootElement();
    for (int i = 0; i < propName.length - 1; i++) {
        element = element.element(propName[i]);
        if (element == null) {
            // This node doesn't match this part of the property name which
            // indicates this property doesn't exist so return empty array.
            return result;
        }
    }
    // We found matching property, return names of children.
    Iterator<Element> iter = element.elementIterator(propName[propName.length - 1]);
    Element prop;
    String value;
    boolean updateEncryption = false;
    while (iter.hasNext()) {
        prop = iter.next();
        // Empty strings are skipped.
        value = prop.getTextTrim();
        if (!"".equals(value)) {
            // check to see if the property is marked as encrypted
            if (JiveGlobals.isPropertyEncrypted(name)) {
                Attribute encrypted = prop.attribute(ENCRYPTED_ATTRIBUTE);
                if (encrypted != null) {
                    value = JiveGlobals.getPropertyEncryptor().decrypt(value);
                } else {
                    // rewrite property as an encrypted value
                    prop.addAttribute(ENCRYPTED_ATTRIBUTE, "true");
                    updateEncryption = true;
                }
            }
            result.add(value);
        }
    }
    if (updateEncryption) {
        Log.info("Rewriting values for XML property " + name + " using encryption");
        saveProperties();
    }
    return result;
}

From source file:org.jivesoftware.whack.container.ComponentFinder.java

License:Open Source License

/**
 * Returns the value of an element selected via an xpath expression from
 * a component's component.xml file./*  w ww  .  j av  a2 s. co m*/
 *
 * @param component the component.
 * @param xpath the xpath expression.
 * @return the value of the element selected by the xpath expression.
 */
private String getElementValue(Component component, String xpath) {
    File componentDir = componentDirs.get(component);
    if (componentDir == null) {
        return null;
    }
    try {
        File componentConfig = new File(componentDir, "component.xml");
        if (componentConfig.exists()) {
            SAXReader saxReader = new SAXReader();
            Document componentXML = saxReader.read(componentConfig);
            Element element = (Element) componentXML.selectSingleNode(xpath);
            if (element != null) {
                return element.getTextTrim();
            }
        }
    } catch (Exception e) {
        manager.getLog().error(e);
    }
    return null;
}

From source file:org.jivesoftware.xmpp.workgroup.Agent.java

License:Open Source License

public void updateAgentInfo(IQ packet) {
    Element agentInfo = packet.getChildElement();
    // Set the new agent's name
    Element element = agentInfo.element("name");
    if (element != null) {
        setNickname(element.getTextTrim());
    }//from  w  w  w .  j  a  v a  2s.  c  om
    // Commented since we don't want the agent to change its JID address
    /*element = agentInfo.element("jid");
    if (element != null) {
    setAgentJID(new JID(element.getTextTrim()));
    }*/
}

From source file:org.jivesoftware.xmpp.workgroup.request.UserRequest.java

License:Open Source License

public UserRequest(IQ packet, Workgroup wg) {
    super();/*w ww  .j a  va 2  s .  c  o m*/
    this.userJID = packet.getFrom();
    this.userID = userJID.toBareJID();
    this.anonymousUser = false;
    this.workgroup = wg;
    // Requests to join a workgroup made using an IQ are assumed to be using a Workgroup
    // compatible client
    this.communicationMethod = WorkgroupCompatibleClient.getInstance();

    Iterator<Element> elementIter = packet.getChildElement().elementIterator();
    while (elementIter.hasNext()) {
        Element element = elementIter.next();
        if ("queue-notifications".equals(element.getName())) {
            setNotify(true);
        } else if ("user".equals(element.getName())) {
            userID = element.attributeValue("id");
            if (userID != null && userID.length() > 0) {
                anonymousUser = !userJID.toString().equals(userID) && !userJID.toBareJID().equals(userID);
            }
        } else if ("metadata".equals(element.getName())) {
            for (Iterator<Element> i = element.elementIterator(); i.hasNext();) {
                Element item = i.next();
                if ("value".equals(item.getName())) {
                    String name = item.attributeValue("name");
                    if (name != null) {
                        metaData.put(name, Arrays.asList(item.getTextTrim()));
                    }
                }
            }
        }
    }

    // Create metadata from submitted form.
    DataForm submittedForm = (DataForm) packet.getExtension(DataForm.ELEMENT_NAME, DataForm.NAMESPACE);

    for (FormField field : submittedForm.getFields()) {
        metaData.put(field.getVariable(), field.getValues());
    }

    // Omit certain items
    metaData.remove("password");
}

From source file:org.lnicholls.galleon.apps.podcasting.Podcasting.java

License:Open Source License

public static Podcast getPodcast(Podcast podcast) {

    PersistentValue persistentValue = PersistentValueManager
            .loadPersistentValue(Podcasting.class.getName() + "."

                    + podcast.getPath());

    String content = persistentValue == null ? null : persistentValue.getValue();

    if (PersistentValueManager.isAged(persistentValue)) {

        try {/*w  w  w  .  j a v a2 s.c  om*/

            String page = Tools.getPage(new URL(podcast.getPath()));

            if (page != null && page.length() > 0)

                content = page;

        } catch (Exception ex) {

            Tools.logException(Podcasting.class, ex, "Could not cache listing: " + podcast.getPath());

        }

    }

    if (content != null) {

        try {

            SAXReader saxReader = new SAXReader();

            StringReader stringReader = new StringReader(content);

            // Document document = saxReader.read(new

            // File("d:/galleon/itunes2.rss.xml"));

            Document document = saxReader.read(stringReader);

            stringReader.close();

            stringReader = null;

            Element root = document.getRootElement(); // check for errors

            if (root != null && root.getName().equals("rss")) {

                Element channel = root.element("channel");

                if (channel != null) {

                    String channelTitle = null;

                    String channelLink = null;

                    String channelDescription = null;

                    String channelSubtitle = null;

                    String channelImage1 = null;

                    String channelImage2 = null;

                    String channelExplicit = null;

                    String channelBlock = null;

                    String channelCategory = null;

                    String channelKeywords = null;

                    String channelSummary = null;

                    String channelTtl = null;

                    String channelAuthor = null;

                    String value = null;

                    if ((value = Tools.getAttribute(channel, "author")) != null) {

                        channelAuthor = value;

                    }

                    if ((value = Tools.getAttribute(channel, "title")) != null) {

                        channelTitle = value;

                    }

                    if ((value = Tools.getAttribute(channel, "link")) != null) {

                        channelLink = value;

                    }

                    if ((value = Tools.getAttribute(channel, "description")) != null) {

                        channelDescription = value;

                    }

                    if ((value = Tools.getAttribute(channel, "subtitle")) != null) {

                        channelSubtitle = value;

                    }

                    for (Iterator i = channel.elementIterator("image"); i.hasNext();) {

                        Element item = (Element) i.next();

                        if (item.element("url") != null) {

                            if ((value = Tools.getAttribute(item, "url")) != null) {

                                channelImage1 = value; // rss

                            }

                        }

                        else

                        if (item.element("image") != null) {

                            item = item.element("image");

                            if ((value = Tools.getAttribute(item, "href")) != null) {

                                channelImage1 = value; // itunes

                            }

                        }

                        else if (item.attribute("href") != null) {

                            channelImage2 = item.attributeValue("href"); // itunes

                        }

                    }

                    if ((value = Tools.getAttribute(channel, "explicit")) != null) {

                        channelExplicit = value;

                    }

                    if ((value = Tools.getAttribute(channel, "block")) != null) {

                        channelBlock = value;

                    }

                    if ((value = Tools.getAttribute(channel, "keywords")) != null) {

                        channelKeywords = value;

                    }

                    if ((value = Tools.getAttribute(channel, "summary")) != null) {

                        channelSummary = value;

                    }

                    if ((value = Tools.getAttribute(channel, "ttl")) != null) {

                        channelTtl = value;

                    }

                    Element categoryElement = channel.element("category");

                    if (categoryElement != null) {

                        if ((value = categoryElement.attributeValue("text")) != null) {

                            channelCategory = value;

                            Element subCategory = categoryElement.element("category");

                            if (subCategory != null) {

                                if ((value = subCategory.attributeValue("text")) != null)

                                    channelCategory = channelCategory + ", " + value;

                            }

                        }

                    }

                    if (channelAuthor != null && channelAuthor.length() > 0)

                        podcast.setAuthor(Tools.cleanHTML(channelAuthor));

                    if (channelTitle != null && channelTitle.length() > 0)

                        podcast.setTitle(Tools.cleanHTML(channelTitle));

                    if (channelLink != null && channelLink.length() > 0)

                        podcast.setLink(channelLink);

                    if (channelDescription != null && channelDescription.length() > 0)

                        podcast.setDescription(Tools.trim(Tools.cleanHTML(channelDescription), 4096));

                    if (channelSubtitle != null && channelSubtitle.length() > 0)

                        podcast.setSubtitle(Tools.trim(Tools.cleanHTML(channelSubtitle), 4096));

                    if (channelImage2 == null) {

                        if (channelImage1 != null

                                && (channelImage1.endsWith(".png") || channelImage1.endsWith(".jpg")
                                        || channelImage1

                                                .endsWith(".gif")))

                            podcast.setImage(channelImage1); // rss

                    } else {

                        if (channelImage2.endsWith(".png") || channelImage2.endsWith(".jpg"))

                            podcast.setImage(channelImage2); // itunes

                    }

                    if (channelBlock != null)

                        podcast.setBlock(new Boolean(!channelBlock.toLowerCase().equals("no")));

                    else

                        podcast.setBlock(Boolean.FALSE);

                    if (channelCategory != null && channelCategory.length() > 0)

                        podcast.setCategory(Tools.cleanHTML(channelCategory));

                    if (channelExplicit != null)

                        podcast.setExplicit(new Boolean(!channelExplicit.toLowerCase().equals("no")));

                    else

                        podcast.setExplicit(Boolean.FALSE);

                    if (channelKeywords != null && channelKeywords.length() > 0)

                        podcast.setKeywords(Tools.cleanHTML(channelKeywords));

                    if (channelSummary != null && channelSummary.length() > 0)

                        podcast.setSummary(Tools.trim(Tools.cleanHTML(channelSummary), 4096));

                    if (channelTtl != null && channelTtl.length() > 0) {

                        try {

                            podcast.setTtl(new Integer(channelTtl));

                        } catch (Exception ex) {

                        }

                    } else

                        podcast.setTtl(new Integer(0));

                    List tracks = podcast.getTracks();

                    if (tracks == null)

                        tracks = new ArrayList();

                    for (Iterator i = channel.elementIterator("item"); i.hasNext();) {

                        Element item = (Element) i.next();

                        String title = null;

                        String description = null;

                        String link = null;

                        String pubDate = null;

                        String guid = null;

                        String category = null;

                        String explicit = null;

                        String author = null;

                        String summary = null;

                        String enclosureUrl = null;

                        String enclosureLength = null;

                        String enclosureType = null;

                        String block = null;

                        String duration = null;

                        String keywords = null;

                        String subtitle = null;

                        if ((value = Tools.getAttribute(item, "title")) != null) {

                            title = value;

                        }

                        if ((value = Tools.getAttribute(item, "description")) != null) {

                            description = value;

                        }

                        if ((value = Tools.getAttribute(item, "link")) != null) {

                            link = value;

                        }

                        if ((value = Tools.getAttribute(item, "pubDate")) != null) {

                            pubDate = value;

                        }

                        if ((value = Tools.getAttribute(item, "guid")) != null) {

                            guid = value;

                        }

                        if ((value = Tools.getAttribute(item, "category")) != null) {

                            category = value;

                        }

                        if ((value = Tools.getAttribute(item, "explicit")) != null) {

                            explicit = value;

                        }

                        for (Iterator j = item.elementIterator("author"); j.hasNext();) {

                            Element authorItem = (Element) j.next();

                            author = authorItem.getTextTrim();

                        }

                        if ((value = Tools.getAttribute(item, "summary")) != null) {

                            summary = value;

                        }

                        Element enclosureElement = item.element("enclosure");

                        if (enclosureElement != null) {

                            if ((value = enclosureElement.attributeValue("url")) != null) {

                                enclosureUrl = value;

                            }

                            if ((value = enclosureElement.attributeValue("length")) != null) {

                                enclosureLength = value;

                            }

                            if ((value = enclosureElement.attributeValue("type")) != null) {

                                enclosureType = value;

                            }

                        }

                        if ((value = Tools.getAttribute(item, "block")) != null) {

                            block = value;

                        }

                        categoryElement = item.element("category");

                        if (categoryElement != null) {

                            if ((value = categoryElement.attributeValue("text")) != null) {

                                category = value;

                                Element subCategory = categoryElement.element("category");

                                if (subCategory != null) {

                                    if ((value = subCategory.attributeValue("text")) != null)

                                        category = category + ", " + value;

                                }

                            }

                        }

                        if ((value = Tools.getAttribute(item, "duration")) != null) {

                            duration = value;

                        }

                        if ((value = Tools.getAttribute(item, "keywords")) != null) {

                            keywords = value;

                        }

                        if ((value = Tools.getAttribute(item, "subtitle")) != null) {

                            subtitle = value;

                        }

                        if (enclosureUrl != null && enclosureUrl.length() > 0
                                && enclosureUrl.endsWith(".mp3")) {

                            PodcastTrack podcastTrack = null;

                            boolean existing = false;

                            for (int k = 0; k < tracks.size(); k++) {

                                PodcastTrack current = (PodcastTrack) tracks.get(k);

                                if (current != null && current.getUrl() != null && enclosureUrl != null

                                        && current.getUrl().equals(enclosureUrl)) {

                                    existing = true;

                                    podcastTrack = current;

                                    break;

                                }

                            }

                            if (podcastTrack == null)

                                podcastTrack = new PodcastTrack();

                            if (title != null && title.length() > 0)

                                podcastTrack.setTitle(Tools.cleanHTML(title));

                            if (description != null && description.length() > 0)

                                podcastTrack.setDescription(Tools.trim(Tools.cleanHTML(description), 4096));

                            if (link != null && link.length() > 0)

                                podcastTrack.setLink(link);

                            if (pubDate != null && pubDate.length() > 0) {

                                try {

                                    podcastTrack.setPublicationDate(new Date(pubDate));

                                } catch (Exception ex) {

                                }

                            }

                            if (guid != null && guid.length() > 0)

                                podcastTrack.setGuid(guid);

                            if (category != null && category.length() > 0)

                                podcastTrack.setCategory(Tools.cleanHTML(category));

                            if (explicit != null && explicit.length() > 0)

                                podcastTrack.setExplicit(new Boolean(!explicit.toLowerCase().equals("no")));

                            else

                                podcastTrack.setExplicit(Boolean.FALSE);

                            if (author != null && author.length() > 0)

                                podcastTrack.setAuthor(Tools.cleanHTML(author));

                            if (summary != null && summary.length() > 0)

                                podcastTrack.setSummary(Tools.trim(Tools.cleanHTML(summary), 4096));

                            if (enclosureUrl != null && enclosureUrl.length() > 0)

                                podcastTrack.setUrl(enclosureUrl);

                            if (enclosureLength != null && enclosureLength.length() > 0) {

                                try {

                                    podcastTrack.setSize(Long.parseLong(enclosureLength));

                                } catch (Exception ex) {

                                }

                            }

                            if (enclosureType != null && enclosureType.length() > 0)

                                podcastTrack.setMimeType(enclosureType);

                            if (block != null && block.length() > 0)

                                podcastTrack.setBlock(new Boolean(!block.toLowerCase().equals("no")));

                            else

                                podcastTrack.setBlock(Boolean.FALSE);

                            if (duration != null && duration.length() > 0) {

                                try {

                                    SimpleDateFormat timeDateFormat = new SimpleDateFormat();

                                    timeDateFormat.applyPattern("HH:mm:ss");

                                    ParsePosition pos = new ParsePosition(0);

                                    Date date = timeDateFormat.parse(duration, pos);

                                    if (date == null) {

                                        timeDateFormat.applyPattern("mm:ss");

                                        date = timeDateFormat.parse(duration, pos);

                                    }

                                    podcastTrack.setDuration(new Long(date.getTime()));

                                } catch (Exception ex) {

                                }

                            }

                            if (keywords != null && keywords.length() > 0)

                                podcastTrack.setKeywords(Tools.cleanHTML(keywords));

                            if (subtitle != null && subtitle.length() > 0)

                                podcastTrack.setSubtitle(Tools.trim(Tools.cleanHTML(subtitle), 4096));

                            if (podcastTrack.getMimeType() == null)

                                podcastTrack.setMimeType(Mp3File.DEFAULT_MIME_TYPE);

                            podcastTrack.setPodcast(podcast.getId());

                            if (!existing)

                                tracks.add(podcastTrack);

                        }

                    }

                    podcast.setTracks(tracks);

                }

            } else {

                ChannelBuilderIF builder = new ChannelBuilder();

                ChannelIF channel = FeedParser

                        .parse(builder, new ByteArrayInputStream((content.getBytes("UTF-8"))));

                if (channel != null) {

                    podcast.setDescription(Tools.cleanHTML(channel.getDescription()));

                    podcast.setDateUpdated(channel.getLastBuildDate());

                    podcast.setTtl(new Integer(channel.getTtl()));

                    List items = getListing(channel);

                    if (items != null && items.size() > 0) {

                        ArrayList tracks = new ArrayList();

                        for (Iterator i = items.iterator(); i.hasNext(); /* Nothing */) {

                            ItemIF item = (ItemIF) i.next();

                            String description = Tools.trim(item.getDescription(), 4096);

                            tracks.add(new PodcastTrack(Tools.cleanHTML(item.getTitle()), null, null,
                                    Tools.trim(

                                            Tools.cleanHTML(item.getDescription()), 4096),
                                    null, null, null, null,

                                    Boolean.FALSE, Boolean.FALSE, null, item.getDate(), item.getEnclosure()

                                            .getLocation().toExternalForm(),
                                    "audio/mpeg", item.getEnclosure()

                                            .getLength(),
                                    0, new Long(0), new Integer(0), 0, 0, podcast.getId(),

                                    new Integer(0), null));

                        }

                        podcast.setTracks(tracks);

                    }

                }

                builder.close();

                builder = null;

            }

            document.clearContent();

            document = null;

            if (PersistentValueManager.isAged(persistentValue)) {

                int ttl = podcast.getTtl().intValue();

                if (ttl < 10)

                    ttl = 60;

                else

                    ttl = 60 * 6;

                PersistentValueManager.savePersistentValue(Podcasting.class.getName() + "." + podcast.getPath(),

                        content, ttl * 60);

            }

        } catch (Exception ex) {

            Tools.logException(Podcasting.class, ex, "Could not download listing: " + podcast.getPath());

            return null;

        }

    }

    return podcast;

}

From source file:org.lnicholls.galleon.apps.videocasting.Videocasting.java

License:Open Source License

public static Videocast getVideocast(Videocast videocast) {

    PersistentValue persistentValue = PersistentValueManager
            .loadPersistentValue(Videocasting.class.getName() + "."

                    + videocast.getPath());

    String content = persistentValue == null ? null : persistentValue.getValue();

    // log.debug("content3="+content);

    if (PersistentValueManager.isAged(persistentValue)) {

        try {/*from ww  w.  j  a v  a 2  s . com*/

            String page = Tools.getPage(new URL(videocast.getPath()));

            if (page != null && page.length() > 0)

                content = page;

        } catch (Exception ex) {

            Tools.logException(Videocasting.class, ex, "Could not cache listing: " + videocast.getPath());

        }

    }

    // log.debug("content4="+content);

    if (content != null) {

        try {

            SAXReader saxReader = new SAXReader();

            StringReader stringReader = new StringReader(content);

            // Document document = saxReader.read(new

            // File("d:/galleon/itunes2.rss.xml"));

            Document document = saxReader.read(stringReader);

            stringReader.close();

            stringReader = null;

            Element root = document.getRootElement(); // check for errors

            if (root != null && root.getName().equals("rss")) {

                Element channel = root.element("channel");

                if (channel != null) {

                    String channelTitle = null;

                    String channelLink = null;

                    String channelDescription = null;

                    String channelSubtitle = null;

                    String channelImage1 = null;

                    String channelImage2 = null;

                    String channelImage3 = null;

                    String channelExplicit = null;

                    String channelBlock = null;

                    String channelCategory = null;

                    String channelKeywords = null;

                    String channelSummary = null;

                    String channelTtl = null;

                    String channelAuthor = null;

                    String value = null;

                    if ((value = Tools.getAttribute(channel, "author")) != null) {

                        channelAuthor = value;

                    }

                    if ((value = Tools.getAttribute(channel, "title")) != null) {

                        channelTitle = value;

                    }

                    if ((value = Tools.getAttribute(channel, "link")) != null) {

                        channelLink = value;

                    }

                    if ((value = Tools.getAttribute(channel, "description")) != null) {

                        channelDescription = value;

                    }

                    if ((value = Tools.getAttribute(channel, "subtitle")) != null) {

                        channelSubtitle = value;

                    }

                    for (Iterator i = channel.elementIterator("image"); i.hasNext();) {

                        Element item = (Element) i.next();

                        if (item.element("url") != null) {

                            if ((value = Tools.getAttribute(item, "url")) != null) {

                                channelImage1 = value; // rss

                            }

                        } else if (item.attribute("href") != null) {

                            channelImage2 = item.attributeValue("href"); // itunes

                        }

                    }

                    Element thumbnailElement = channel.element("thumbnail");

                    if (thumbnailElement != null) {

                        if ((value = thumbnailElement.attributeValue("url")) != null) {

                            channelImage3 = value;

                        }

                    }

                    if ((value = Tools.getAttribute(channel, "explicit")) != null) {

                        channelExplicit = value;

                    }

                    if ((value = Tools.getAttribute(channel, "block")) != null) {

                        channelBlock = value;

                    }

                    if ((value = Tools.getAttribute(channel, "keywords")) != null) {

                        channelKeywords = value;

                    }

                    if ((value = Tools.getAttribute(channel, "summary")) != null) {

                        channelSummary = value;

                    }

                    if ((value = Tools.getAttribute(channel, "ttl")) != null) {

                        channelTtl = value;

                    }

                    Element categoryElement = channel.element("category");

                    if (categoryElement != null) {

                        if ((value = categoryElement.attributeValue("text")) != null) {

                            channelCategory = value;

                            Element subCategory = categoryElement.element("category");

                            if (subCategory != null) {

                                if ((value = subCategory.attributeValue("text")) != null)

                                    channelCategory = channelCategory + ", " + value;

                            }

                        }

                    }

                    if (channelAuthor != null && channelAuthor.length() > 0)

                        videocast.setAuthor(Tools.cleanHTML(channelAuthor));

                    if (channelTitle != null && channelTitle.length() > 0)

                        videocast.setTitle(Tools.cleanHTML(channelTitle));

                    if (channelLink != null && channelLink.length() > 0)

                        videocast.setLink(channelLink);

                    if (channelDescription != null && channelDescription.length() > 0)

                        videocast.setDescription(Tools.trim(Tools.cleanHTML(channelDescription), 4096));

                    if (channelSubtitle != null && channelSubtitle.length() > 0)

                        videocast.setSubtitle(Tools.trim(Tools.cleanHTML(channelSubtitle), 4096));

                    if (channelImage2 == null) {

                        if (channelImage1 != null

                                && (channelImage1.endsWith(".png") || channelImage1.endsWith(".jpg")
                                        || channelImage1

                                                .endsWith(".gif")))

                            videocast.setImage(channelImage1); // rss

                        else

                            videocast.setImage(channelImage3);

                    } else {

                        if (channelImage2.endsWith(".png") || channelImage2.endsWith(".jpg"))

                            videocast.setImage(channelImage2); // itunes

                    }

                    if (channelBlock != null)

                        videocast.setBlock(new Boolean(!channelBlock.toLowerCase().equals("no")));

                    else

                        videocast.setBlock(Boolean.FALSE);

                    if (channelCategory != null && channelCategory.length() > 0)

                        videocast.setCategory(Tools.cleanHTML(channelCategory));

                    if (channelExplicit != null)

                        videocast.setExplicit(new Boolean(!channelExplicit.toLowerCase().equals("no")));

                    else

                        videocast.setExplicit(Boolean.FALSE);

                    if (channelKeywords != null && channelKeywords.length() > 0)

                        videocast.setKeywords(Tools.cleanHTML(channelKeywords));

                    if (channelSummary != null && channelSummary.length() > 0)

                        videocast.setSummary(Tools.trim(channelSummary, 4096));

                    if (channelTtl != null && channelTtl.length() > 0) {

                        try {

                            videocast.setTtl(new Integer(channelTtl));

                        } catch (Exception ex) {

                        }

                    } else

                        videocast.setTtl(new Integer(0));

                    List tracks = videocast.getTracks();

                    if (tracks == null)

                        tracks = new ArrayList();

                    for (Iterator i = channel.elementIterator("item"); i.hasNext();) {

                        Element item = (Element) i.next();

                        String title = null;

                        String description = null;

                        String link = null;

                        String pubDate = null;

                        String guid = null;

                        String category = null;

                        String explicit = null;

                        String author = null;

                        String summary = null;

                        String enclosureUrl = null;

                        String enclosureLength = null;

                        String enclosureType = null;

                        String block = null;

                        String duration = null;

                        String keywords = null;

                        String subtitle = null;

                        if ((value = Tools.getAttribute(item, "title")) != null) {

                            title = value;

                        }

                        if ((value = Tools.getAttribute(item, "description")) != null) {

                            description = value;

                        }

                        if ((value = Tools.getAttribute(item, "link")) != null) {

                            link = value;

                        }

                        if ((value = Tools.getAttribute(item, "pubDate")) != null) {

                            pubDate = value;

                        }

                        if ((value = Tools.getAttribute(item, "guid")) != null) {

                            guid = value;

                        }

                        if ((value = Tools.getAttribute(item, "category")) != null) {

                            category = value;

                        }

                        if ((value = Tools.getAttribute(item, "explicit")) != null) {

                            explicit = value;

                        }

                        for (Iterator j = item.elementIterator("author"); j.hasNext();) {

                            Element authorItem = (Element) j.next();

                            author = authorItem.getTextTrim();

                        }

                        if ((value = Tools.getAttribute(item, "summary")) != null) {

                            summary = value;

                        }

                        Element enclosureElement = item.element("enclosure");

                        if (enclosureElement != null) {

                            if ((value = enclosureElement.attributeValue("url")) != null) {

                                enclosureUrl = value;

                            }

                            if ((value = enclosureElement.attributeValue("length")) != null) {

                                enclosureLength = value;

                            }

                            if ((value = enclosureElement.attributeValue("type")) != null) {

                                enclosureType = value;

                            }

                        }

                        if ((value = Tools.getAttribute(item, "block")) != null) {

                            block = value;

                        }

                        categoryElement = item.element("category");

                        if (categoryElement != null) {

                            if ((value = categoryElement.attributeValue("text")) != null) {

                                category = value;

                                Element subCategory = categoryElement.element("category");

                                if (subCategory != null) {

                                    if ((value = subCategory.attributeValue("text")) != null)

                                        category = category + ", " + value;

                                }

                            }

                        }

                        if ((value = Tools.getAttribute(item, "duration")) != null) {

                            duration = value;

                        }

                        if ((value = Tools.getAttribute(item, "keywords")) != null) {

                            keywords = value;

                        }

                        if ((value = Tools.getAttribute(item, "subtitle")) != null) {

                            subtitle = value;

                        }

                        if (enclosureUrl != null && enclosureUrl.length() > 0) {

                            VideocastTrack videocastTrack = null;

                            boolean existing = false;

                            for (int k = 0; k < tracks.size(); k++) {

                                VideocastTrack current = (VideocastTrack) tracks.get(k);

                                if (current != null && current.getUrl() != null && enclosureUrl != null

                                        && current.getUrl().equals(enclosureUrl)) {

                                    existing = true;

                                    videocastTrack = current;

                                    break;

                                }

                            }

                            if (videocastTrack == null)

                                videocastTrack = new VideocastTrack();

                            if (title != null && title.length() > 0 && (videocastTrack.getTitle() == null
                                    || videocastTrack.getTitle().trim().length() == 0))

                                videocastTrack.setTitle(Tools.cleanHTML(title));

                            if (description != null && description.length() > 0)

                                videocastTrack.setDescription(Tools.trim(Tools.cleanHTML(description), 4096));

                            if (link != null && link.length() > 0)

                                videocastTrack.setLink(link);

                            if (pubDate != null && pubDate.length() > 0) {

                                try {

                                    videocastTrack.setPublicationDate(new Date(pubDate));

                                } catch (Exception ex) {

                                }

                            }

                            if (guid != null && guid.length() > 0)

                                videocastTrack.setGuid(guid);

                            if (category != null && category.length() > 0)

                                videocastTrack.setCategory(Tools.cleanHTML(category));

                            if (explicit != null && explicit.length() > 0)

                                videocastTrack.setExplicit(new Boolean(!explicit.toLowerCase().equals("no")));

                            else

                                videocastTrack.setExplicit(Boolean.FALSE);

                            if (author != null && author.length() > 0)

                                videocastTrack.setAuthor(Tools.cleanHTML(author));

                            if (summary != null && summary.length() > 0)

                                videocastTrack.setSummary(Tools.trim(Tools.cleanHTML(summary), 4096));

                            if (enclosureUrl != null && enclosureUrl.length() > 0)

                                videocastTrack.setUrl(enclosureUrl);

                            if (enclosureLength != null && enclosureLength.length() > 0) {

                                try {

                                    videocastTrack.setSize(Long.parseLong(enclosureLength));

                                } catch (Exception ex) {

                                }

                            }

                            if (enclosureType != null && enclosureType.length() > 0)

                                videocastTrack.setMimeType(enclosureType);

                            if (block != null && block.length() > 0)

                                videocastTrack.setBlock(new Boolean(!block.toLowerCase().equals("no")));

                            else

                                videocastTrack.setBlock(Boolean.FALSE);

                            if (duration != null && duration.length() > 0) {

                                try {

                                    SimpleDateFormat timeDateFormat = new SimpleDateFormat();

                                    timeDateFormat.applyPattern("HH:mm:ss");

                                    ParsePosition pos = new ParsePosition(0);

                                    Date date = timeDateFormat.parse(duration, pos);

                                    if (date == null) {

                                        timeDateFormat.applyPattern("mm:ss");

                                        date = timeDateFormat.parse(duration, pos);

                                    }

                                    videocastTrack.setDuration(new Long(date.getTime()));

                                } catch (Exception ex) {

                                }

                            }

                            if (keywords != null && keywords.length() > 0)

                                videocastTrack.setKeywords(Tools.cleanHTML(keywords));

                            if (subtitle != null && subtitle.length() > 0)

                                videocastTrack.setSubtitle(Tools.trim(Tools.cleanHTML(subtitle), 4096));

                            if (videocastTrack.getMimeType() == null)

                                videocastTrack.setMimeType(VideoFile.DEFAULT_MIME_TYPE);

                            videocastTrack.setVideocast(videocast.getId());

                            if (!existing)

                                tracks.add(videocastTrack);

                        }

                    }

                    videocast.setTracks(tracks);

                }

            } else {

                ChannelBuilderIF builder = new ChannelBuilder();

                ChannelIF channel = FeedParser

                        .parse(builder, new ByteArrayInputStream((content.getBytes("UTF-8"))));

                if (channel != null) {

                    videocast.setDescription(Tools.cleanHTML(channel.getDescription()));

                    videocast.setDateUpdated(channel.getLastBuildDate());

                    videocast.setTtl(new Integer(channel.getTtl()));

                    List items = getListing(channel);

                    if (items != null && items.size() > 0) {

                        ArrayList tracks = new ArrayList();

                        for (Iterator i = items.iterator(); i.hasNext(); /* Nothing */) {

                            ItemIF item = (ItemIF) i.next();

                            String description = Tools.trim(item.getDescription(), 4096);

                            tracks.add(new VideocastTrack(Tools.cleanHTML(item.getTitle()), null, null,
                                    Tools.trim(

                                            Tools.cleanHTML(item.getDescription()), 4096),
                                    null, null, null, null,

                                    Boolean.FALSE, Boolean.FALSE, null, item.getDate(), item.getEnclosure()

                                            .getLocation().toExternalForm(),
                                    "audio/mpeg", item.getEnclosure()

                                            .getLength(),
                                    0, new Long(0), new Integer(0), 0, 0, videocast.getId(),

                                    new Integer(0), null));

                        }

                        videocast.setTracks(tracks);

                    }

                }

                builder.close();

                builder = null;

            }

            document.clearContent();

            document = null;

            if (PersistentValueManager.isAged(persistentValue)) {

                int ttl = videocast.getTtl().intValue();

                if (ttl < 10)

                    ttl = 60;

                else

                    ttl = 60 * 6;

                PersistentValueManager.savePersistentValue(

                        Videocasting.class.getName() + "." + videocast.getPath(), content, ttl * 60);

            }

        } catch (Exception ex) {

            Tools.logException(Videocasting.class, ex, "Could not download listing: " + videocast.getPath());

            return null;

        }

    }

    return videocast;

}