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 GmbH & Co. KG, 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.workplace.tools.accounts;
029
030import org.opencms.file.CmsGroup;
031import org.opencms.jsp.CmsJspActionElement;
032import org.opencms.main.CmsException;
033import org.opencms.main.CmsIllegalArgumentException;
034import org.opencms.main.OpenCms;
035import org.opencms.security.CmsOrganizationalUnit;
036import org.opencms.security.CmsRole;
037import org.opencms.security.I_CmsPrincipal;
038import org.opencms.util.CmsStringUtil;
039import org.opencms.util.CmsUUID;
040import org.opencms.widgets.CmsCheckboxWidget;
041import org.opencms.widgets.CmsDisplayWidget;
042import org.opencms.widgets.CmsInputWidget;
043import org.opencms.widgets.CmsTextareaWidget;
044import org.opencms.workplace.CmsDialog;
045import org.opencms.workplace.CmsWidgetDialog;
046import org.opencms.workplace.CmsWidgetDialogParameter;
047import org.opencms.workplace.CmsWorkplaceSettings;
048import org.opencms.workplace.tools.CmsToolManager;
049
050import java.util.ArrayList;
051import java.util.HashMap;
052import java.util.List;
053import java.util.Map;
054
055import javax.servlet.http.HttpServletRequest;
056
057/**
058 * Skeleton dialog to create a new group or edit an existing group in the administration view.<p>
059 *
060 * @since 6.0.0
061 */
062public abstract class A_CmsEditGroupDialog extends CmsWidgetDialog {
063
064    /** localized messages Keys prefix. */
065    public static final String KEY_PREFIX = "group";
066
067    /** Defines which pages are valid for this dialog. */
068    public static final String[] PAGES = {"page1"};
069
070    /** Request parameter name for the group id. */
071    public static final String PARAM_GROUPID = "groupid";
072
073    /** Request parameter name for the group name. */
074    public static final String PARAM_GROUPNAME = "groupname";
075
076    /** The user object that is edited on this dialog. */
077    protected CmsGroup m_group;
078
079    /** Stores the value of the request parameter for the group id. */
080    private String m_paramGroupid;
081
082    /** Stores the value of the request parameter for the organizational unit fqn. */
083    private String m_paramOufqn;
084
085    /** Auxiliary Property for better representation of the bean parentId property. */
086    private String m_parentGroup;
087
088    /**
089     * Public constructor with JSP action element.<p>
090     *
091     * @param jsp an initialized JSP action element
092     */
093    public A_CmsEditGroupDialog(CmsJspActionElement jsp) {
094
095        super(jsp);
096    }
097
098    /**
099     * Commits the edited group to the db.<p>
100     */
101    @Override
102    public void actionCommit() {
103
104        List<Throwable> errors = new ArrayList<Throwable>();
105
106        try {
107            // if new create it first
108            if (m_group.getId() == null) {
109                CmsGroup newGroup = getCms().createGroup(
110                    m_paramOufqn + m_group.getSimpleName(),
111                    m_group.getDescription(),
112                    m_group.isEnabled() ? I_CmsPrincipal.FLAG_ENABLED : I_CmsPrincipal.FLAG_DISABLED,
113                    getParentGroup());
114                m_group = newGroup;
115            } else {
116                if (getParentGroup() != null) {
117                    m_group.setParentId(getCms().readGroup(getParentGroup()).getId());
118                } else {
119                    m_group.setParentId(CmsUUID.getNullUUID());
120                }
121            }
122            // write the edited group
123            getCms().writeGroup(m_group);
124            // refresh the list
125            Map<?, ?> objects = (Map<?, ?>)getSettings().getListObject();
126            if (objects != null) {
127                objects.remove(getListClass());
128                objects.remove(A_CmsUsersList.class.getName());
129            }
130        } catch (Throwable t) {
131            errors.add(t);
132        }
133
134        if (errors.isEmpty() && isNewGroup()) {
135            if ((getParamCloseLink() != null) && (getParamCloseLink().indexOf("path=" + getListRootPath()) > -1)) {
136                // set closelink
137                Map<String, String[]> argMap = new HashMap<String, String[]>();
138                argMap.put("groupid", new String[] {m_group.getId().toString()});
139                argMap.put("groupname", new String[] {m_group.getName()});
140                argMap.put("oufqn", new String[] {m_paramOufqn});
141                setParamCloseLink(CmsToolManager.linkForToolPath(getJsp(), getListRootPath() + "/edit", argMap));
142            }
143        }
144        // set the list of errors to display when saving failed
145        setCommitErrors(errors);
146    }
147
148    /**
149     * Returns the description of the parent ou.<p>
150     *
151     * @return the description of the parent ou
152     */
153    public String getAssignedOu() {
154
155        try {
156            return OpenCms.getOrgUnitManager().readOrganizationalUnit(getCms(), getParamOufqn()).getDescription(
157                getLocale()) + " (" + CmsOrganizationalUnit.SEPARATOR + getParamOufqn() + ")";
158        } catch (CmsException e) {
159            return null;
160        }
161    }
162
163    /**
164     * Returns the localized description of a group.<p>
165     *
166     * @return the localized description of a group
167     */
168    public String getDescription() {
169
170        return m_group.getDescription(getLocale());
171    }
172
173    /**
174     * Returns the simple name of the group object.<p>
175     *
176     * @return the simple name of the group object
177     */
178    public String getName() {
179
180        return m_group.getSimpleName();
181    }
182
183    /**
184     * Returns the user id parameter value.<p>
185     *
186     * @return the user id parameter value
187     */
188    public String getParamGroupid() {
189
190        return m_paramGroupid;
191    }
192
193    /**
194     * Returns the organizational unit parameter value.<p>
195     *
196     * @return the organizational unit parameter value
197     */
198    public String getParamOufqn() {
199
200        return m_paramOufqn;
201    }
202
203    /**
204     * Returns the parent Group name.<p>
205     *
206     * @return the parent Group name
207     */
208    public String getParentGroup() {
209
210        return m_parentGroup;
211    }
212
213    /**
214     * The method is just needed for displaying reasons.<p>
215     *
216     * @param assignedOu nothing to do with this parameter
217     */
218    public void setAssignedOu(String assignedOu) {
219
220        // nothing will be done here, just to avoid warnings
221        assignedOu.length();
222    }
223
224    /**
225     * Sets the description for a group.<p>
226     *
227     * @param description the description for a group
228     */
229    public void setDescription(String description) {
230
231        m_group.setDescription(description);
232    }
233
234    /**
235     * Sets the name of the group object.<p>
236     *
237     * @param name the name of the group object
238     */
239    public void setName(String name) {
240
241        m_group.setName(getParamOufqn() + name);
242    }
243
244    /**
245     * Sets the user id parameter value.<p>
246     *
247     * @param userId the user id parameter value
248     */
249    public void setParamGroupid(String userId) {
250
251        m_paramGroupid = userId;
252    }
253
254    /**
255     * Sets the organizational unit parameter value.<p>
256     *
257     * @param ouFqn the organizational unit parameter value
258     */
259    public void setParamOufqn(String ouFqn) {
260
261        if (ouFqn == null) {
262            ouFqn = "";
263        }
264        m_paramOufqn = ouFqn;
265    }
266
267    /**
268     * Sets the parent Group name.<p>
269     *
270     * @param parentGroup the parent Group name to set
271     */
272    public void setParentGroup(String parentGroup) {
273
274        if (CmsStringUtil.isEmpty(parentGroup) || parentGroup.equals("null") || parentGroup.equals("none")) {
275            parentGroup = null;
276        }
277        if (parentGroup != null) {
278            try {
279                getCms().readGroup(parentGroup);
280            } catch (CmsException e) {
281                throw new CmsIllegalArgumentException(e.getMessageContainer());
282            }
283        }
284        m_parentGroup = parentGroup;
285    }
286
287    /**
288     * Creates the dialog HTML for all defined widgets of the named dialog (page).<p>
289     *
290     * This overwrites the method from the super class to create a layout variation for the widgets.<p>
291     *
292     * @param dialog the dialog (page) to get the HTML for
293     * @return the dialog HTML for all defined widgets of the named dialog (page)
294     */
295    @Override
296    protected String createDialogHtml(String dialog) {
297
298        StringBuffer result = new StringBuffer(1024);
299
300        result.append(createWidgetTableStart());
301        // show error header once if there were validation errors
302        result.append(createWidgetErrorHeader());
303
304        if (dialog.equals(PAGES[0])) {
305            // create the widgets for the first dialog page
306            result.append(dialogBlockStart(key(Messages.GUI_GROUP_EDITOR_LABEL_IDENTIFICATION_BLOCK_0)));
307            result.append(createWidgetTableStart());
308            result.append(createDialogRowsHtml(0, 3));
309            result.append(createWidgetTableEnd());
310            result.append(dialogBlockEnd());
311        }
312
313        result.append(createWidgetTableEnd());
314        return result.toString();
315    }
316
317    /**
318     * Creates the list of widgets for this dialog.<p>
319     */
320    @Override
321    protected void defineWidgets() {
322
323        // initialize the user object to use for the dialog
324        initGroupObject();
325        setKeyPrefix(KEY_PREFIX);
326
327        // widgets to display
328        if ((m_group.getId() == null) && isEditable(m_group)) {
329            addWidget(new CmsWidgetDialogParameter(this, "name", PAGES[0], new CmsInputWidget()));
330        } else {
331            addWidget(new CmsWidgetDialogParameter(this, "name", PAGES[0], new CmsDisplayWidget()));
332        }
333        if (isEditable(m_group)) {
334            addWidget(new CmsWidgetDialogParameter(this, "description", PAGES[0], new CmsTextareaWidget()));
335            addWidget(new CmsWidgetDialogParameter(this, "assignedOu", PAGES[0], new CmsDisplayWidget()));
336            addWidget(new CmsWidgetDialogParameter(m_group, "enabled", PAGES[0], new CmsCheckboxWidget()));
337        } else {
338            addWidget(new CmsWidgetDialogParameter(this, "description", PAGES[0], new CmsDisplayWidget()));
339            addWidget(new CmsWidgetDialogParameter(this, "assignedOu", PAGES[0], new CmsDisplayWidget()));
340            addWidget(new CmsWidgetDialogParameter(m_group, "enabled", PAGES[0], new CmsDisplayWidget()));
341        }
342    }
343
344    /**
345     * Returns the dialog class name of the list to refresh.<p>
346     *
347     * @return the list dialog class name
348     */
349    protected abstract String getListClass();
350
351    /**
352     * Returns the root path for the list tool.<p>
353     *
354     * @return the root path
355     */
356    protected abstract String getListRootPath();
357
358    /**
359     * @see org.opencms.workplace.CmsWidgetDialog#getPageArray()
360     */
361    @Override
362    protected String[] getPageArray() {
363
364        return PAGES;
365    }
366
367    /**
368     * Initializes the group object to work with depending on the dialog state and request parameters.<p>
369     *
370     * Two initializations of the group object on first dialog call are possible:
371     * <ul>
372     * <li>edit an existing group</li>
373     * <li>create a new group</li>
374     * <li>view an existing group overview</li>
375     * <li>view an existing group short info</li>
376     * </ul>
377     */
378    protected void initGroupObject() {
379
380        Object o = null;
381
382        try {
383            if (CmsStringUtil.isEmpty(getParamAction()) || CmsDialog.DIALOG_INITIAL.equals(getParamAction())) {
384                // edit an existing user, get the user object from db
385                m_group = getCms().readGroup(new CmsUUID(getParamGroupid()));
386            } else {
387                // this is not the initial call, get the user object from session
388                o = getDialogObject();
389                m_group = (CmsGroup)o;
390                // test
391                m_group.getId();
392            }
393            if ((m_group.getParentId() != null) && !m_group.getParentId().isNullUUID()) {
394                setParentGroup(getCms().getParent(m_group.getName()).getName());
395            }
396        } catch (Exception e) {
397            // create a new user object
398            m_group = new CmsGroup();
399            setParentGroup(null);
400        }
401    }
402
403    /**
404     * @see org.opencms.workplace.CmsWorkplace#initMessages()
405     */
406    @Override
407    protected void initMessages() {
408
409        // add specific dialog resource bundle
410        addMessages(Messages.get().getBundleName());
411        // add default resource bundles
412        super.initMessages();
413    }
414
415    /**
416     * @see org.opencms.workplace.CmsWorkplace#initWorkplaceRequestValues(org.opencms.workplace.CmsWorkplaceSettings, javax.servlet.http.HttpServletRequest)
417     */
418    @Override
419    protected void initWorkplaceRequestValues(CmsWorkplaceSettings settings, HttpServletRequest request) {
420
421        // initialize parameters and dialog actions in super implementation
422        super.initWorkplaceRequestValues(settings, request);
423
424        // save the current state of the group (may be changed because of the widget values)
425        setDialogObject(m_group);
426    }
427
428    /**
429     * Tests if the given group is editable or not.<p>
430     *
431     * Not editable means that no property can be changed.<p>
432     *
433     * @param group the group to test
434     *
435     * @return the editable flag
436     */
437    protected abstract boolean isEditable(CmsGroup group);
438
439    /**
440     * @see org.opencms.workplace.CmsWidgetDialog#validateParamaters()
441     */
442    @Override
443    protected void validateParamaters() throws Exception {
444
445        OpenCms.getRoleManager().checkRole(getCms(), CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParamOufqn()));
446        if (!isNewGroup()) {
447            // test the needed parameters
448            getCms().readGroup(new CmsUUID(getParamGroupid())).getName();
449        }
450    }
451
452    /**
453     * Checks if the new Group dialog has to be displayed.<p>
454     *
455     * @return <code>true</code> if the new Group dialog has to be displayed
456     */
457    private boolean isNewGroup() {
458
459        return getCurrentToolPath().equals(getListRootPath() + "/new");
460    }
461}