/*-
 * Copyright (c) 2005-2011 Lucas Holt
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
package com.justjournal.ctl;

import com.justjournal.core.Settings;
import com.justjournal.model.Entry;
import com.justjournal.model.Security;
import com.justjournal.repository.EntryRepository;
import com.justjournal.repository.SecurityDao;
import com.justjournal.rss.Rss;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Display recent blog entries in RSS format.
 *
 * @author Lucas Holt
 * @version $Id: RecentBlogs.java,v 1.15 2011/07/01 11:54:31 laffer1 Exp $
 */
@Controller
@RequestMapping("/RecentBlogs")
public class RecentBlogsController {
    private static final Logger log = Logger.getLogger(RecentBlogsController.class);

    @Autowired
    private EntryRepository entryRepository;
    @Autowired
    private SecurityDao securityDao;
    @Autowired
    private Settings set;

    @Cacheable("recentblogs")
    @RequestMapping(method = RequestMethod.GET, produces = "application/rss+xml")
    public
    @ResponseBody
    String get(HttpServletResponse response) {
        response.setContentType("application/rss+xml;charset=UTF-8");
        response.setDateHeader("Expires", System.currentTimeMillis() + 1000 * 60);
        response.setHeader("Cache-Control", "max-age=60, private, proxy-revalidate");

        // Create an RSS object, set the required
        // properties (title, description language, url)
        // and write it to the sb output.
        try {
            Rss rss = new Rss();

            final java.util.GregorianCalendar gregorianCalendar = new java.util.GregorianCalendar(java.util.TimeZone.getTimeZone("UTC"));
            gregorianCalendar.setTime(new java.util.Date());

            rss.setTitle("JJ New Posts");
            rss.setLink(set.getBaseUri());
            rss.setDescription("New blog posts on Just Journal");
            rss.setLanguage("en-us");
            rss.setCopyright("Copyright " + gregorianCalendar.get(Calendar.YEAR) + " JustJournal.com and its blog account owners.");
            rss.setWebMaster(set.getSiteAdminEmail() + " (" + set.getSiteAdmin() + ")");
            rss.setManagingEditor(set.getSiteAdminEmail() + " (" + set.getSiteAdmin() + ")");
            rss.setSelfLink(set.getBaseUri() + "RecentBlogs");


            Security security = securityDao.findOne(2); // public
            Pageable pageable = new PageRequest(1,15);
            Page<Entry> entries = entryRepository.findBySecurityOrderByDateDesc(security, pageable);

            Map<String, Entry> map = new HashMap<String, Entry>();
            int count = 0;
            for (Entry e : entries) {
                if (count == 15) break;
                if (map.containsKey(e.getUser().getUsername())) continue;

                map.put(e.getUser().getUsername(), e);
                count++;
            }

            rss.populate(map.values());

            Date d = rss.getNewestEntryDate();

            if (d != null)
                response.setDateHeader("Last-Modified", d.getTime());
            else
                response.setDateHeader("Last-Modified", System.currentTimeMillis());

            return rss.toXml();
        } catch (Exception e) {
            // oops we goofed somewhere.  Its not in the original spec
            // how to handle error conditions with rss.
            // html back isn't good, but what do we do?
            log.debug(e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            } catch (IOException e1) {
                log.debug(e1);
            }
        }

        return "";
    }
}

@@ -2805,16 +2805,53 @@
 s set;%0A%0A
+    @Autowired%0A    private Rss rss;%0A%0A
     @Cac
@@ -2958,19 +2958,8 @@
 l%22)%0A
-    public%0A
     
@@ -2976,16 +2976,23 @@
 ody%0A    
+public 
 String g
@@ -2994,16 +2994,22 @@
 ing get(
+final 
 HttpServ
@@ -3438,41 +3438,8 @@
 ry %7B
-%0A            Rss rss = new Rss();
 %0A%0A  
@@ -4205,17 +4205,17 @@
 ogs%22);%0A%0A
-%0A
+ 
         
@@ -4217,16 +4217,21 @@
         
+final
  Securit
@@ -4285,24 +4285,30 @@
             
+final 
 Pageable pag
@@ -4350,16 +4350,22 @@
         
+final 
 Page%3CEnt
@@ -4458,16 +4458,22 @@
         
+final 
 Map%3CStri
@@ -4563,16 +4563,22 @@
    for (
+final 
 Entry e 
@@ -4622,16 +4622,36 @@
 t == 15)
+%0A                   
  break;%0A
@@ -4713,16 +4713,36 @@
 name()))
+%0A                   
  continu
@@ -5178,16 +5178,22 @@
  catch (
+final 
 Exceptio
@@ -5529,16 +5529,22 @@
  catch (
+final 
 IOExcept

fix constructor