no.dusken.aranea.admin.control.ImportStvMediaController.java Source code

Java tutorial

Introduction

Here is the source code for no.dusken.aranea.admin.control.ImportStvMediaController.java

Source

/*
 Copyright 2006 - 2010 Under Dusken
    
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
    
 http://www.apache.org/licenses/LICENSE-2.0
    
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
package no.dusken.aranea.admin.control;

import no.dusken.aranea.model.MediaResource;
import no.dusken.aranea.model.MediaType;
import no.dusken.aranea.service.MediaResourceService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.List;

//This is a refactored ImportSamfundetEventController.
public class ImportStvMediaController implements Controller {

    private MediaResourceService mediaResourceService;

    private String cacheDirectory;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private boolean isImporting = false;

    private String feedUrl;

    /**
    * This method is called by the timer
    */
    public void doImport() {
        if (!isImporting) {
            try {
                handleRequest(null, null);
            } catch (Exception e) {
                log.error("Could not import", e);
            } finally {
                isImporting = false;
            }
        }
    }

    public ModelAndView handleRequest(HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse) throws Exception {
        if (isImporting) {
            log.error("import already running");
            return new ModelAndView("redirect:/");

        } else {
            isImporting = true;
        }

        /*
         * parses the podcastfeed from stv to mediaResource
         */
        URI uri = new URI(feedUrl);
        URL url = uri.toURL();
        File file = new File(cacheDirectory + "/" + "feed.xml");
        FileUtils.copyURLToFile(url, file);
        Document doc = parseXmlFile(file);
        // get the root elememt
        Element docEle = doc.getDocumentElement();

        // get a nodelist of <item> elements
        NodeList nl = docEle.getElementsByTagName("item");
        if (nl != null && nl.getLength() > 0) {
            for (int i = 0; i < nl.getLength(); i++) {

                // get the item element
                Element el = (Element) nl.item(i);
                //get the mediaresource
                MediaResource mr = getMediaResource(el);

                if (!isInDb(mr)) {
                    mediaResourceService.saveOrUpdate(mr);
                    log.info("Imported media, url: {}", mr.getUrlToResource());
                }

            }
        }
        return new ModelAndView("redirect:/");
    }

    private MediaResource getMediaResource(Element empEl) {

        MediaResource mr = new MediaResource();

        mr.setTitle(getTextValue(empEl, "title"));
        mr.setDescription(getTextValue(empEl, "description"));
        mr.setUrlToResource(getTextValue(empEl, "url"));
        mr.setMediaType(MediaType.VIDEO);
        return mr;
    }

    private Document parseXmlFile(File file) {
        Document dom = null;
        // get the factory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {

            // Using factory get an instance of document builder
            DocumentBuilder db = dbf.newDocumentBuilder();

            // parse using builder to get DOM representation of the XML file
            dom = db.parse(file);

        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (SAXException se) {
            se.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return dom;
    }

    /**
    * I take a xml element and the tag name, look for the tag and get the text
    * content i.e for <employee><name>John</name></employee> xml snippet if
    * the Element points to employee node and tagName is name I will return John
    */
    private String getTextValue(Element ele, String tagName) {
        String textVal = null;

        NodeList nl = ele.getElementsByTagName(tagName);
        if (nl != null && nl.getLength() > 0) {
            Element el = (Element) nl.item(0);
            textVal = el.getFirstChild().getNodeValue();
        }

        return textVal;
    }

    private boolean isInDb(MediaResource mr) {
        List<MediaResource> old = mediaResourceService.getMediaResourceByUrl(mr.getUrlToResource());
        return old.size() > 0;
    }

    @Required
    public void setMediaResourceService(MediaResourceService mediaResourceService) {
        this.mediaResourceService = mediaResourceService;
    }

    @Required
    public void setCacheDirectory(String dir) {
        this.cacheDirectory = dir;
    }

    @Required
    public void setFeedUrl(String feedUrl) {
        this.feedUrl = feedUrl;
    }
}