001: /*
002: * File : $Source: /usr/local/cvs/opencms/src-modules/org/opencms/workplace/tools/accounts/CmsUserDataImportDialog.java,v $
003: * Date : $Date: 2008-02-27 12:05:27 $
004: * Version: $Revision: 1.4 $
005: *
006: * This library is part of OpenCms -
007: * the Open Source Content Management System
008: *
009: * Copyright (c) 2002 - 2008 Alkacon Software GmbH (http://www.alkacon.com)
010: *
011: * This library is free software; you can redistribute it and/or
012: * modify it under the terms of the GNU Lesser General Public
013: * License as published by the Free Software Foundation; either
014: * version 2.1 of the License, or (at your option) any later version.
015: *
016: * This library is distributed in the hope that it will be useful,
017: * but WITHOUT ANY WARRANTY; without even the implied warranty of
018: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
019: * Lesser General Public License for more details.
020: *
021: * For further information about Alkacon Software GmbH, please see the
022: * company website: http://www.alkacon.com
023: *
024: * For further information about OpenCms, please see the
025: * project website: http://www.opencms.org
026: *
027: * You should have received a copy of the GNU Lesser General Public
028: * License along with this library; if not, write to the Free Software
029: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
030: */
031:
032: package org.opencms.workplace.tools.accounts;
033:
034: import org.opencms.i18n.CmsEncoder;
035: import org.opencms.jsp.CmsJspActionElement;
036: import org.opencms.main.CmsIllegalArgumentException;
037: import org.opencms.main.CmsRuntimeException;
038: import org.opencms.util.CmsRequestUtil;
039: import org.opencms.util.CmsStringUtil;
040: import org.opencms.util.CmsXsltUtil;
041: import org.opencms.widgets.CmsGroupWidget;
042: import org.opencms.widgets.CmsHttpUploadWidget;
043: import org.opencms.widgets.CmsInputWidget;
044: import org.opencms.widgets.CmsSelectWidget;
045: import org.opencms.workplace.CmsDialog;
046: import org.opencms.workplace.CmsWidgetDialogParameter;
047: import org.opencms.workplace.CmsWorkplaceSettings;
048:
049: import java.io.BufferedReader;
050: import java.io.File;
051: import java.io.FileOutputStream;
052: import java.io.FileReader;
053: import java.io.IOException;
054: import java.util.ArrayList;
055: import java.util.HashMap;
056: import java.util.Iterator;
057: import java.util.List;
058: import java.util.Map;
059:
060: import javax.servlet.ServletException;
061: import javax.servlet.http.HttpServletRequest;
062: import javax.servlet.http.HttpServletResponse;
063: import javax.servlet.jsp.PageContext;
064:
065: import org.apache.commons.fileupload.FileItem;
066:
067: /**
068: * Dialog to import user data.<p>
069: *
070: * @author Raphael Schnuck
071: *
072: * @version $Revision: 1.4 $
073: *
074: * @since 6.5.6
075: */
076: public class CmsUserDataImportDialog extends
077: A_CmsUserDataImexportDialog {
078:
079: /** localized messages Keys prefix. */
080: public static final String KEY_PREFIX = "userdata.import";
081:
082: /** The path to the file to import. */
083: private String m_importFile;
084:
085: /** The password to use in the import. */
086: private String m_password;
087:
088: /**
089: * Public constructor with JSP action element.<p>
090: *
091: * @param jsp an initialized JSP action element
092: */
093: public CmsUserDataImportDialog(CmsJspActionElement jsp) {
094:
095: super (jsp);
096: }
097:
098: /**
099: * Public constructor with JSP variables.<p>
100: *
101: * @param context the JSP page context
102: * @param req the JSP request
103: * @param res the JSP response
104: */
105: public CmsUserDataImportDialog(PageContext context,
106: HttpServletRequest req, HttpServletResponse res) {
107:
108: this (new CmsJspActionElement(context, req, res));
109: }
110:
111: /**
112: * @see org.opencms.workplace.tools.accounts.A_CmsUserDataImexportDialog#actionCommit()
113: */
114: public void actionCommit() throws IOException, ServletException {
115:
116: List errors = new ArrayList();
117:
118: // get the file item from the multipart request
119: Iterator it = getMultiPartFileItems().iterator();
120: FileItem fi = null;
121: while (it.hasNext()) {
122: fi = (FileItem) it.next();
123: if (fi.getName() != null) {
124: // found the file object, leave iteration
125: break;
126: } else {
127: // this is no file object, check next item
128: continue;
129: }
130: }
131:
132: if (fi != null
133: && CmsStringUtil.isNotEmptyOrWhitespaceOnly(fi
134: .getName())) {
135: byte[] content = fi.get();
136: File importFile = File.createTempFile("import_users",
137: ".csv");
138: m_importFile = importFile.getAbsolutePath();
139:
140: FileOutputStream fileOutput = new FileOutputStream(
141: importFile);
142: fileOutput.write(content);
143: fileOutput.close();
144: fi.delete();
145:
146: FileReader fileReader = new FileReader(importFile);
147: BufferedReader bufferedReader = new BufferedReader(
148: fileReader);
149: String line = bufferedReader.readLine();
150:
151: if (line != null) {
152: List colDefs = CmsStringUtil.splitAsList(line,
153: CmsXsltUtil.getPreferredDelimiter(line));
154: if (!colDefs.contains("name")) {
155: errors
156: .add(new CmsRuntimeException(
157: Messages
158: .get()
159: .container(
160: Messages.ERR_USERDATA_IMPORT_CSV_MISSING_NAME_0)));
161: }
162: if ((line.indexOf("password") == -1)
163: && CmsStringUtil
164: .isEmptyOrWhitespaceOnly(m_password)) {
165: errors
166: .add(new CmsRuntimeException(
167: Messages
168: .get()
169: .container(
170: Messages.ERR_USERDATA_IMPORT_CSV_MISSING_PASSWORD_0)));
171: }
172: }
173: bufferedReader.close();
174: } else {
175: errors
176: .add(new CmsIllegalArgumentException(
177: Messages
178: .get()
179: .container(
180: Messages.ERR_USERDATA_IMPORT_NO_CONTENT_0)));
181: }
182:
183: if (errors.isEmpty()) {
184: Map params = new HashMap();
185: params.put("groups", CmsStringUtil.collectionAsString(
186: getGroups(), ","));
187: params.put("roles", CmsStringUtil.collectionAsString(
188: getRoles(), ","));
189: params.put("importfile", m_importFile);
190: params.put("password", m_password);
191: params.put(A_CmsOrgUnitDialog.PARAM_OUFQN, getParamOufqn());
192: // set action parameter to initial dialog call
193: params
194: .put(CmsDialog.PARAM_ACTION,
195: CmsDialog.DIALOG_INITIAL);
196:
197: getToolManager().jspForwardTool(this ,
198: getCurrentToolPath() + "/list", params);
199: }
200: // set the list of errors to display when something goes wrong
201: setCommitErrors(errors);
202: }
203:
204: /**
205: * @see org.opencms.workplace.CmsWidgetDialog#dialogButtonsCustom()
206: */
207: public String dialogButtonsCustom() {
208:
209: StringBuffer result = new StringBuffer(256);
210: result.append(dialogButtonRow(HTML_START));
211: result.append("<input name=\"ok\" value=\"");
212: result
213: .append(key(org.opencms.workplace.Messages.GUI_DIALOG_BUTTON_CONTINUE_0)
214: + "\"");
215: result.append(" type=\"submit\"");
216: result.append(" class=\"dialogbutton\"");
217: result.append(">\n");
218: dialogButtonsHtml(result, BUTTON_CANCEL, "");
219: result.append(dialogButtonRow(HTML_END));
220: return result.toString();
221: }
222:
223: /**
224: * Returns the path of the file to import.<p>
225: *
226: * @return the path of the file to import
227: */
228: public String getImportFile() {
229:
230: return m_importFile;
231: }
232:
233: /**
234: * Returns the password to set during import.<p>
235: *
236: * @return the password to set during import
237: */
238: public String getPassword() {
239:
240: return m_password;
241: }
242:
243: /**
244: * Sets the path of the import file.<p>
245: *
246: * @param importFile the import file path
247: */
248: public void setImportFile(String importFile) {
249:
250: m_importFile = importFile;
251: }
252:
253: /**
254: * Sets the password to use during import.<p>
255: *
256: * @param password the password to use during import
257: */
258: public void setPassword(String password) {
259:
260: m_password = password;
261: }
262:
263: /**
264: * Creates the dialog HTML for all defined widgets of the named dialog (page).<p>
265: *
266: * This overwrites the method from the super class to create a layout variation for the widgets.<p>
267: *
268: * @param dialog the dialog (page) to get the HTML for
269: * @return the dialog HTML for all defined widgets of the named dialog (page)
270: */
271: protected String createDialogHtml(String dialog) {
272:
273: StringBuffer result = new StringBuffer(1024);
274:
275: result.append(createWidgetTableStart());
276: // show error header once if there were validation errors
277: result.append(createWidgetErrorHeader());
278:
279: if (dialog.equals(PAGES[0])) {
280: // create the widgets for the first dialog page
281: result
282: .append(dialogBlockStart(key(Messages.GUI_USERDATA_IMPORT_LABEL_HINT_BLOCK_0)));
283: result
284: .append(key(Messages.GUI_USERDATA_IMPORT_LABEL_HINT_TEXT_0));
285: result.append(dialogBlockEnd());
286: result
287: .append(dialogBlockStart(key(Messages.GUI_USERDATA_IMPORT_LABEL_DATA_BLOCK_0)));
288: result.append(createWidgetTableStart());
289: result.append(createDialogRowsHtml(0, 3));
290: result.append(createWidgetTableEnd());
291: result.append(dialogBlockEnd());
292: }
293:
294: result.append(createWidgetTableEnd());
295: return result.toString();
296: }
297:
298: /**
299: * @see org.opencms.workplace.CmsWidgetDialog#defaultActionHtmlContent()
300: */
301: protected String defaultActionHtmlContent() {
302:
303: StringBuffer result = new StringBuffer(2048);
304: result
305: .append(
306: "<form name=\"EDITOR\" id=\"EDITOR\" method=\"post\" action=\"")
307: .append(getDialogRealUri());
308: result
309: .append(
310: "\" class=\"nomargin\" onsubmit=\"return submitAction('")
311: .append(DIALOG_OK)
312: .append(
313: "', null, 'EDITOR');\" enctype=\"multipart/form-data\">\n");
314: result.append(dialogContentStart(getDialogTitle()));
315: result.append(buildDialogForm());
316: result.append(dialogContentEnd());
317: result.append(dialogButtonsCustom());
318: result.append(paramsAsHidden());
319: if (getParamFramename() == null) {
320: result.append("\n<input type=\"hidden\" name=\"").append(
321: PARAM_FRAMENAME).append("\" value=\"\">\n");
322: }
323: result.append("</form>\n");
324: result.append(getWidgetHtmlEnd());
325: return result.toString();
326: }
327:
328: /**
329: * @see org.opencms.workplace.tools.accounts.A_CmsUserDataImexportDialog#defineWidgets()
330: */
331: protected void defineWidgets() {
332:
333: initImportObject();
334: setKeyPrefix(KEY_PREFIX);
335:
336: addWidget(new CmsWidgetDialogParameter(this , "groups",
337: PAGES[0], new CmsGroupWidget(null, null,
338: getParamOufqn())));
339: addWidget(new CmsWidgetDialogParameter(this , "roles", PAGES[0],
340: new CmsSelectWidget(getSelectRoles())));
341: addWidget(new CmsWidgetDialogParameter(this , "password",
342: PAGES[0], new CmsInputWidget()));
343: addWidget(new CmsWidgetDialogParameter(this , "importFile",
344: PAGES[0], new CmsHttpUploadWidget()));
345: }
346:
347: /**
348: * @see org.opencms.workplace.CmsWidgetDialog#fillWidgetValues(javax.servlet.http.HttpServletRequest)
349: */
350: protected void fillWidgetValues(HttpServletRequest request) {
351:
352: Map parameters;
353: if (getMultiPartFileItems() != null) {
354: parameters = CmsRequestUtil.readParameterMapFromMultiPart(
355: getCms().getRequestContext().getEncoding(),
356: getMultiPartFileItems());
357: } else {
358: parameters = request.getParameterMap();
359: }
360: Map processedParameters = new HashMap();
361: Iterator p = parameters.entrySet().iterator();
362: // make sure all "hidden" widget parameters are decoded
363: while (p.hasNext()) {
364: Map.Entry entry = (Map.Entry) p.next();
365: String key = (String) entry.getKey();
366: String[] values = (String[]) entry.getValue();
367: if (key.startsWith(HIDDEN_PARAM_PREFIX)) {
368: // this is an encoded hidden parameter
369: key = key.substring(HIDDEN_PARAM_PREFIX.length());
370: String[] newValues = new String[values.length];
371: for (int l = 0; l < values.length; l++) {
372: newValues[l] = CmsEncoder.decode(values[l],
373: getCms().getRequestContext().getEncoding());
374: }
375: values = newValues;
376: }
377: processedParameters.put(key, values);
378: }
379:
380: // now process the parameters
381: m_widgetParamValues = new HashMap();
382: Iterator i = getWidgets().iterator();
383:
384: while (i.hasNext()) {
385: // check for all widget base parameters
386: CmsWidgetDialogParameter base = (CmsWidgetDialogParameter) i
387: .next();
388:
389: List params = new ArrayList();
390: int maxOccurs = base.getMaxOccurs();
391:
392: boolean onPage = false;
393: if (base.isCollectionBase()) {
394: // for a collection base, check if we are on the page where the collection base is shown
395: if (CmsStringUtil.isNotEmpty(getParamAction())
396: && !DIALOG_INITIAL.equals(getParamAction())) {
397: // if no action set (usually for first display of dialog) make sure all values are shown
398: // DIALOG_INITIAL is a special value for the first display and must be handled the same way
399: String page = getParamPage();
400: // keep in mind that since the paramPage will be set AFTER the widget values are filled,
401: // so the first time this page is called from another page the following will result to "false",
402: // but for every "submit" on the page this will be "true"
403: onPage = CmsStringUtil.isEmpty(page)
404: || CmsStringUtil.isEmpty(base
405: .getDialogPage())
406: || base.getDialogPage().equals(page);
407: }
408: }
409:
410: for (int j = 0; j < maxOccurs; j++) {
411: // check for all possible values in the request parameters
412: String id = CmsWidgetDialogParameter.createId(base
413: .getName(), j);
414:
415: boolean required = (params.size() < base.getMinOccurs())
416: || (processedParameters.get(id) != null)
417: || (!onPage && base.hasValue(j));
418:
419: if (required) {
420: CmsWidgetDialogParameter param = new CmsWidgetDialogParameter(
421: base, params.size(), j);
422: param.setKeyPrefix(KEY_PREFIX);
423: base.getWidget().setEditorValue(getCms(),
424: processedParameters, this , param);
425: params.add(param);
426: }
427: }
428: m_widgetParamValues.put(base.getName(), params);
429: }
430: }
431:
432: /**
433: * Initializes the message info object to work with depending on the dialog state and request parameters.<p>
434: */
435: protected void initImportObject() {
436:
437: try {
438: if (CmsStringUtil.isEmpty(getParamAction())
439: || CmsDialog.DIALOG_INITIAL
440: .equals(getParamAction())) {
441: // create a new list
442: setGroups(new ArrayList());
443: setRoles(new ArrayList());
444: } else {
445: // this is not the initial call, get the message info object from session
446: setGroups((List) ((Map) getDialogObject())
447: .get("groups"));
448: setRoles((List) ((Map) getDialogObject()).get("roles"));
449: m_importFile = (String) ((Map) getDialogObject())
450: .get("importfile");
451: m_password = (String) ((Map) getDialogObject())
452: .get("password");
453: }
454: } catch (Exception e) {
455: // create a new list
456: setGroups(new ArrayList());
457: setRoles(new ArrayList());
458: }
459: }
460:
461: /**
462: * @see org.opencms.workplace.CmsWorkplace#initWorkplaceRequestValues(org.opencms.workplace.CmsWorkplaceSettings, javax.servlet.http.HttpServletRequest)
463: */
464: protected void initWorkplaceRequestValues(
465: CmsWorkplaceSettings settings, HttpServletRequest request) {
466:
467: // initialize parameters and dialog actions in super implementation
468: super .initWorkplaceRequestValues(settings, request);
469:
470: HashMap objectsMap = new HashMap();
471: objectsMap.put("groups", getGroups());
472: objectsMap.put("roles", getRoles());
473: objectsMap.put("importfile", m_importFile);
474: objectsMap.put("password", m_password);
475:
476: // save the current state of the message (may be changed because of the widget values)
477: setDialogObject(objectsMap);
478: }
479: }
|