001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software, please see the
018 * company website: http://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: http://www.opencms.org
022 *
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 */
027
028package org.opencms.ui.apps.dbmanager;
029
030import org.opencms.db.CmsUserSettings;
031import org.opencms.file.CmsObject;
032import org.opencms.main.CmsException;
033import org.opencms.main.CmsLog;
034import org.opencms.main.OpenCms;
035import org.opencms.synchronize.CmsSynchronizeSettings;
036import org.opencms.ui.A_CmsUI;
037import org.opencms.ui.CmsVaadinUtils;
038import org.opencms.ui.apps.Messages;
039import org.opencms.ui.components.CmsRemovableFormRow;
040import org.opencms.ui.components.fileselect.CmsPathSelectField;
041
042import java.util.ArrayList;
043import java.util.HashSet;
044import java.util.List;
045import java.util.Set;
046
047import org.apache.commons.logging.Log;
048
049import com.vaadin.v7.data.Property.ValueChangeEvent;
050import com.vaadin.v7.data.Property.ValueChangeListener;
051import com.vaadin.v7.data.Validator;
052import com.vaadin.v7.ui.AbstractField;
053import com.vaadin.ui.Button;
054import com.vaadin.ui.Button.ClickEvent;
055import com.vaadin.v7.ui.CheckBox;
056import com.vaadin.ui.Component;
057import com.vaadin.ui.FormLayout;
058import com.vaadin.v7.ui.TextField;
059import com.vaadin.v7.ui.VerticalLayout;
060
061/**
062 * Synchronization layout class.<p>
063 */
064public class CmsDbSynchronizationView extends VerticalLayout {
065
066    /**
067     * Validator for the resource fields.<p>
068     */
069    class ResourceValidator implements Validator {
070
071        /**vaadin serial id.*/
072        private static final long serialVersionUID = -1513193444185009615L;
073
074        /**
075         * @see com.vaadin.data.Validator#validate(java.lang.Object)
076         */
077        public void validate(Object value) throws InvalidValueException {
078
079            String resourceName = (String)value;
080            if (synchroEnabled() & (resourceName == null)) {
081                throw new InvalidValueException(
082                    CmsVaadinUtils.getMessageText(Messages.GUI_DATABASEAPP_SYNC_VALIDATION_EMPTY_RESOURCES_0));
083            }
084
085            try {
086                m_cms.readResource(resourceName);
087            } catch (CmsException e) {
088                throw new InvalidValueException(
089                    CmsVaadinUtils.getMessageText(
090                        Messages.GUI_DATABASEAPP_SYNC_VALIDATION_RESOURCE_NOT_FOUND_1,
091                        resourceName));
092            }
093        }
094    }
095
096    /**
097     * Validator for the target.<p>
098     */
099    class TargetValidator implements Validator {
100
101        /**vaadin serial id.*/
102        private static final long serialVersionUID = 4404089964412111711L;
103
104        /**
105         * @see com.vaadin.data.Validator#validate(java.lang.Object)
106         */
107        public void validate(Object value) throws InvalidValueException {
108
109            String val = (String)value;
110            if (synchroEnabled() & val.isEmpty()) {
111                throw new InvalidValueException(
112                    CmsVaadinUtils.getMessageText(Messages.GUI_DATABASEAPP_SYNC_VALIDATION_EMPTY_TARGET_0));
113            }
114            if (synchroEnabled()) {
115                try {
116                    m_synchronizeSettings.setDestinationPathInRfs(val);
117                } catch (Throwable t) {
118                    throw new InvalidValueException(
119                        CmsVaadinUtils.getMessageText(Messages.GUI_DATABASEAPP_SYNC_VALIDATION_EMPTY_TARGET_0));
120                }
121            }
122        }
123
124    }
125
126    /**vaadin serial id.*/
127    private static final long serialVersionUID = -794938118093564562L;
128
129    /** The logger for this class. */
130    static Log LOG = CmsLog.getLog(CmsDbSynchronizationView.class.getName());
131
132    /** The synchronize settings which are edited on this dialog. */
133    CmsSynchronizeSettings m_synchronizeSettings;
134
135    /**Vaadin component.*/
136    private Button m_addResource;
137
138    /**Vaadin component.*/
139    private Button m_ok;
140
141    /**Vaadin component.*/
142    private FormLayout m_resources;
143
144    /**Root CmsObject. */
145    protected CmsObject m_cms;
146
147    /**Vaadin component.*/
148    private TextField m_target;
149
150    /**Vaadin component.*/
151    private CheckBox m_enabled;
152
153    /**Instance of calling app.*/
154    private CmsDbSynchronizationApp m_app;
155
156    /**Components which have to be validated.*/
157    private Set<AbstractField<String>> m_componentsToValidate = new HashSet<AbstractField<String>>();
158
159    /**
160     * Public constructor.<p>
161     * @param app instance of calling app
162     */
163    public CmsDbSynchronizationView(CmsDbSynchronizationApp app) {
164        CmsVaadinUtils.readAndLocalizeDesign(this, CmsVaadinUtils.getWpMessagesForCurrentLocale(), null);
165        m_app = app;
166        m_componentsToValidate.add(m_target);
167        m_cms = initCms(A_CmsUI.getCmsObject());
168        CmsUserSettings userSettings = new CmsUserSettings(m_cms);
169
170        m_synchronizeSettings = userSettings.getSynchronizeSettings();
171        if (m_synchronizeSettings == null) {
172            m_synchronizeSettings = new CmsSynchronizeSettings();
173            m_synchronizeSettings.setEnabled(false);
174        }
175
176        m_app.setRefreshButton(m_synchronizeSettings.isEnabled());
177
178        initUI();
179
180        m_target.addValueChangeListener(new ValueChangeListener() {
181
182            private static final long serialVersionUID = 5508413459469395463L;
183
184            public void valueChange(ValueChangeEvent event) {
185
186                setOkButtonEnabled(true);
187
188            }
189        });
190
191        m_enabled.addValueChangeListener(new ValueChangeListener() {
192
193            private static final long serialVersionUID = -5921001488632416603L;
194
195            public void valueChange(ValueChangeEvent event) {
196
197                setOkButtonEnabled(true);
198
199            }
200        });
201
202        m_addResource.addClickListener(new Button.ClickListener() {
203
204            private static final long serialVersionUID = 2169629308804189534L;
205
206            public void buttonClick(ClickEvent event) {
207
208                addResource("");
209            }
210        });
211
212        m_ok.addClickListener(new Button.ClickListener() {
213
214            private static final long serialVersionUID = -5083450266085163340L;
215
216            public void buttonClick(ClickEvent event) {
217
218                removeEmptyResourceFields();
219                addValidators();
220                if (isValid()) {
221                    submit();
222                    setOkButtonEnabled(false);
223                }
224            }
225        });
226    }
227
228    /**
229     * Adds a resource to form.<p>
230     *
231     * @param path of resource to add
232     */
233    protected void addResource(String path) {
234
235        CmsPathSelectField field = new CmsPathSelectField();
236        field.setCmsObject(m_cms);
237        field.setUseRootPaths(true);
238        field.setValue(path);
239        field.addValueChangeListener(new ValueChangeListener() {
240
241            private static final long serialVersionUID = 8646438704383992571L;
242
243            public void valueChange(ValueChangeEvent event) {
244
245                setOkButtonEnabled(true);
246
247            }
248        });
249        m_componentsToValidate.add(field);
250        CmsRemovableFormRow<CmsPathSelectField> row = new CmsRemovableFormRow<CmsPathSelectField>(
251            field,
252            CmsVaadinUtils.getMessageText(Messages.GUI_DATABASEAPP_SYNC_REMOVE_RESOURCE_0));
253        row.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_DATABASEAPP_SYNC_RESOURCE_0));
254        row.setRemoveRunnable(new Runnable() {
255
256            public void run() {
257
258                setOkButtonEnabled(true);
259            }
260        });
261        m_resources.addComponent(row);
262    }
263
264    /**
265     * Adds validators to the input fields.<p>
266     */
267    protected void addValidators() {
268
269        m_target.removeAllValidators();
270        m_target.addValidator(new TargetValidator());
271
272        for (Component c : m_componentsToValidate) {
273            if (c instanceof CmsPathSelectField) {
274                ((CmsPathSelectField)c).removeAllValidators();
275                ((CmsPathSelectField)c).addValidator(new ResourceValidator());
276            }
277        }
278    }
279
280    /**
281     * Checks if synchronization is enabled.<p>
282     *
283     * @return true if synchronization is enabled, false otherwise
284     */
285    protected boolean isEnabledSych() {
286
287        return m_synchronizeSettings.isEnabled();
288    }
289
290    /**
291     * Checks if all fields are valid.<p>
292     *
293     * @return true if fields are valid
294     */
295    protected boolean isValid() {
296
297        for (AbstractField<String> component : m_componentsToValidate) {
298            if (!component.isValid()) {
299                return false;
300            }
301        }
302        return true;
303    }
304
305    /**
306     * Removes empty resource fields.<p>
307     */
308    protected void removeEmptyResourceFields() {
309
310        Set<Component> componentsToRemove = new HashSet<Component>();
311        int count = 0;
312        Component lastElement = null;
313
314        for (Component c : m_resources) {
315            if (c instanceof CmsRemovableFormRow<?>) {
316                count++;
317                AbstractField<?> field = (AbstractField<?>)((CmsRemovableFormRow)c).getInput();
318                String value = (String)(field.getValue());
319                if (value.isEmpty()) {
320                    componentsToRemove.add(c);
321                    lastElement = c;
322                }
323            }
324        }
325
326        //if all fields are empty -> keep one of them to attach validator to
327        if (componentsToRemove.size() == count) {
328            componentsToRemove.remove(lastElement);
329        }
330
331        if (count == 0) {
332            addResource("");
333        }
334
335        for (Component c : componentsToRemove) {
336            m_resources.removeComponent(c);
337            m_componentsToValidate.remove(c);
338        }
339    }
340
341    /**
342     * En/ Disables the ok button.<p>
343     *
344     * @param enable boolean indicates if button should be enabled
345     */
346    protected void setOkButtonEnabled(boolean enable) {
347
348        m_ok.setEnabled(enable);
349    }
350
351    /**
352     * Submits the form.<p>
353     */
354    protected void submit() {
355
356        m_synchronizeSettings.setEnabled(m_enabled.getValue().booleanValue());
357        m_synchronizeSettings.setSourceListInVfs(getResourcePaths());
358        try {
359            // set the synchronize settings
360            CmsUserSettings userSettings = new CmsUserSettings(A_CmsUI.getCmsObject());
361            userSettings.setSynchronizeSettings(m_synchronizeSettings);
362            userSettings.save(A_CmsUI.getCmsObject());
363        } catch (CmsException e) {
364            LOG.error("Unable to set synchro settings", e);
365        }
366        CmsUserSettings userSettings = new CmsUserSettings(A_CmsUI.getCmsObject());
367        m_synchronizeSettings = userSettings.getSynchronizeSettings();
368        m_app.setRefreshButton(m_synchronizeSettings.isEnabled());
369    }
370
371    /**
372     * Is the enabled button clicked.<p>
373     *
374     * @return true, if synchro should be enabled
375     */
376    protected boolean synchroEnabled() {
377
378        return m_enabled.getValue().booleanValue();
379    }
380
381    /**
382     * Reads entered resources from form.<p>
383     *
384     * @return List of resource paths
385     */
386    private List<String> getResourcePaths() {
387
388        List<String> res = new ArrayList<String>();
389        for (Component c : m_resources) {
390            if (c instanceof CmsRemovableFormRow<?>) {
391                AbstractField<?> field = (AbstractField<?>)(((CmsRemovableFormRow)c).getInput());
392                res.add((String)(field.getValue()));
393            }
394        }
395        return res;
396    }
397
398    /**
399     * Clones given CmsObject and switches to root site.<p>
400     *
401     * @param cms given CmsObject
402     * @return cloned CmsObject
403     */
404    private CmsObject initCms(CmsObject cms) {
405
406        try {
407            cms = OpenCms.initCmsObject(cms);
408        } catch (CmsException e) {
409            LOG.error("Unable to init CmsObject");
410        }
411        cms.getRequestContext().setSiteRoot("");
412        return cms;
413    }
414
415    /**
416     * Initializes UI.<p>
417     */
418    private void initUI() {
419
420        m_enabled.setValue(new Boolean(m_synchronizeSettings.isEnabled()));
421        if (m_synchronizeSettings.getDestinationPathInRfs() != null) {
422            m_target.setValue(m_synchronizeSettings.getDestinationPathInRfs());
423        }
424        List<String> resources = m_synchronizeSettings.getSourceListInVfs();
425        for (String resource : resources) {
426            addResource(resource);
427        }
428        setOkButtonEnabled(false);
429    }
430}