View Javadoc

1   /**
2    * This file Copyright (c) 2013 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.module.rssaggregator.app.subapps.aggregationconfig;
35  
36  import info.magnolia.cms.security.AccessManager;
37  import info.magnolia.cms.security.Permission;
38  import info.magnolia.context.MgnlContext;
39  import info.magnolia.i18nsystem.SimpleTranslator;
40  import info.magnolia.jcr.util.PropertyUtil;
41  import info.magnolia.module.data.commands.ImportCommand;
42  import info.magnolia.module.rssaggregator.RSSAggregatorConstants;
43  import info.magnolia.module.rssaggregator.RSSAggregatorNodeTypes;
44  import info.magnolia.module.rssaggregator.app.subapps.aggregationconfig.view.RSSAggregatorConfigurationView;
45  import info.magnolia.module.rssaggregator.generator.CollectStatisticsCommand;
46  import info.magnolia.module.rssaggregator.generator.PlanetDataGenerator;
47  import info.magnolia.repository.RepositoryConstants;
48  import info.magnolia.ui.api.app.AppContext;
49  import info.magnolia.ui.api.context.UiContext;
50  import info.magnolia.ui.api.view.View;
51  import info.magnolia.ui.vaadin.overlay.MessageStyleTypeEnum;
52  
53  import javax.inject.Inject;
54  import javax.jcr.Node;
55  import javax.jcr.RepositoryException;
56  import javax.jcr.Session;
57  import javax.jcr.query.Query;
58  import javax.jcr.query.QueryManager;
59  import javax.jcr.query.QueryResult;
60  
61  import org.slf4j.Logger;
62  import org.slf4j.LoggerFactory;
63  
64  
65  /**
66   * Presenter class, holds logic of
67   * {@link info.magnolia.module.rssaggregator.app.subapps.aggregationconfig.RSSAggregatorConfigurationSubApp} sub-app.
68   */
69  public class RSSAggregatorConfigurationPresenter implements RSSAggregatorConfigurationView.Listener {
70  
71      private static final String IMPORT_ERROR_LABEL = "rssAggregator.config.notification.import_error";
72  
73      private static final String TASKS = "/modules/data/config/importers/rssaggregator/automatedExecution";
74  
75      private static final String PLANET_DATA_PATH = "/modules/scheduler/config/jobs/generatePlanetData";
76  
77      private static final String PLANET_STATISTICS_PATH = "/modules/scheduler/config/jobs/collectPlanetStatistics";
78  
79      private static final String IMPORT_COMPLETE_LABEL = "rssAggregator.config.notification.import_complete";
80  
81      private static final String SETTINGS_CHANGED_LABEL = "rssAggregator.config.notification.settings_changed";
82  
83      public static final String PLANET_DATA_CHANGED_LABEL = "rssAggregator.config.notification.planet_data_changed";
84  
85      public static final String STATISTICS_COLLECTED_LABEL = "rssAggregator.config.notification.stats_collected";
86  
87      public static final String PLANET_AGGREGATOR_QUERY_TEMPLATE = "SELECT * FROM [%s] WHERE planetFeed = true";
88  
89      private Logger log = LoggerFactory.getLogger(getClass());
90  
91      private RSSAggregatorConfigurationView view;
92  
93      private UiContext uiContext;
94  
95      private SimpleTranslator translator;
96  
97      @Inject
98      public RSSAggregatorConfigurationPresenter(RSSAggregatorConfigurationView view, AppContext uiContext, SimpleTranslator translator) {
99          this.view = view;
100         this.uiContext = uiContext;
101         this.translator = translator;
102     }
103 
104     public View start() {
105         view.setListener(this);
106         return view;
107     }
108 
109     protected boolean checkPermissions(String repository, String basePath, long permissionType) {
110         AccessManager accessManager = MgnlContext.getAccessManager(repository);
111         if (accessManager != null) {
112             if (!accessManager.isGranted(basePath, permissionType)) {
113                 return false;
114             }
115         }
116         return true;
117     }
118 
119     @Override
120     public void onManualImport() {
121         if (!checkPermissions(RSSAggregatorConstants.WORKSPACE, "/", Permission.WRITE)) {
122             uiContext.openNotification(MessageStyleTypeEnum.ERROR, false, translator.translate(IMPORT_ERROR_LABEL));
123         } else {
124             ImportCommand cmd = new ImportCommand();
125             cmd.setImporter("rssaggregator");
126             cmd.execute(MgnlContext.getInstance());
127             uiContext.openNotification(MessageStyleTypeEnum.INFO, true, translator.translate(IMPORT_COMPLETE_LABEL));
128         }
129     }
130 
131     @Override
132     public void onAutomaticImportChanged(int periodMinutes) {
133         try {
134             Session session = MgnlContext.getJCRSession("config");
135             Node execution = session.getNode(TASKS);
136             execution.setProperty("enabled", true);
137             execution.setProperty("cron", "0 0/" + periodMinutes + " * * * *");
138             session.save();
139             uiContext.openNotification(MessageStyleTypeEnum.INFO, true, translator.translate(SETTINGS_CHANGED_LABEL));
140         } catch (RepositoryException e) {
141             displayException(e, "Failed to update automatic update period");
142         }
143 
144     }
145 
146     @Override
147     public void onAutomaticPlanetUpdateChanged(int value) {
148         try {
149             Session session = MgnlContext.getJCRSession("config");
150             Node planetDataScheduler = session.getNode(PLANET_DATA_PATH);
151             PropertyUtil.setProperty(planetDataScheduler, "active", true);
152             PropertyUtil.setProperty(planetDataScheduler, "cron", "0 0/" + value + " * * * *");
153             session.save();
154             uiContext.openNotification(MessageStyleTypeEnum.INFO, true, SETTINGS_CHANGED_LABEL);
155         }  catch (RepositoryException e) {
156             displayException(e, "Failed to change planet update period: ");
157         }
158     }
159 
160     @Override
161     public void onPlanetDataManualUpdate() {
162         try {
163             PlanetDataGenerator pdg = new PlanetDataGenerator();
164             pdg.execute(MgnlContext.getInstance());
165             uiContext.openNotification(MessageStyleTypeEnum.INFO, true, translator.translate(PLANET_DATA_CHANGED_LABEL));
166         } catch (Exception e) {
167             displayException(e, "Failed to update planet data: ");
168         }
169 
170     }
171 
172     @Override
173     public void onPlanetStatisticsManualUpdate() {
174         CollectStatisticsCommand csc = new CollectStatisticsCommand();
175         try {
176             csc.execute(MgnlContext.getInstance());
177             uiContext.openNotification(MessageStyleTypeEnum.INFO, true, translator.translate(STATISTICS_COLLECTED_LABEL));
178         } catch (Exception e) {
179             displayException(e, "Failed to collect statistics: ");
180         }
181     }
182 
183     @Override
184     public void onPlanetStatisticsAutomaticUpdatePeriodChanged(int value) {
185         try {
186             Session session = MgnlContext.getJCRSession("config");
187             Node planetStatisticsScheduler = session.getNode(PLANET_STATISTICS_PATH);
188             PropertyUtil.setProperty(planetStatisticsScheduler, "active", true);
189             PropertyUtil.setProperty(planetStatisticsScheduler, "cron", "0 0/" + value + " * * * *");
190             session.save();
191             uiContext.openNotification(MessageStyleTypeEnum.INFO, true, translator.translate(SETTINGS_CHANGED_LABEL));
192         } catch (RepositoryException e) {
193             displayException(e, "Failed to update planet update period: ");
194         }
195 
196     }
197 
198     private void displayException(Exception e, String msg) {
199         uiContext.openNotification(MessageStyleTypeEnum.ERROR, false, msg + e.getMessage());
200         log.error(msg, e);
201     }
202 
203     public void updateConfiguration() {
204         view.setDataImportPeriod(parseAutoUpdatePeriod(TASKS));
205         view.setPlanetStatsImportPeriod(parseAutoUpdatePeriod(PLANET_STATISTICS_PATH));
206         view.setPlanetDataImportPeriod(parseAutoUpdatePeriod(PLANET_DATA_PATH));
207 
208         boolean isPlanetVisible;
209         try {
210             QueryManager queryManager = MgnlContext.getJCRSession(RSSAggregatorConstants.WORKSPACE).getWorkspace().getQueryManager();
211             String queryStr = String.format(PLANET_AGGREGATOR_QUERY_TEMPLATE, RSSAggregatorNodeTypes.RSSAggregator.NAME);
212             Query q = queryManager.createQuery(queryStr, Query.JCR_SQL2);
213             QueryResult result = q.execute();
214             isPlanetVisible = result.getNodes().hasNext();
215         } catch (RepositoryException e) {
216             isPlanetVisible = false;
217             log.warn("Problem occurred while checking planet config visibility " + e.getMessage());
218         }
219 
220         view.setPlanetConfigVisible(isPlanetVisible);
221     }
222 
223     private int parseAutoUpdatePeriod(String path) {
224         try {
225             Session session = MgnlContext.getJCRSession(RepositoryConstants.CONFIG);
226             Node execution = session.getNode(path);
227             String[] cron = execution.getProperty("cron").getString().split(" ");
228             if (cron[1].indexOf('/') < 0) {
229                 return 0;
230             } else {
231                 return Integer.parseInt(cron[1].substring(cron[1].indexOf('/') + 1));
232             }
233         } catch (RepositoryException e) {
234             return 0;
235         }
236     }
237 }