KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > workplace > explorer > CmsNewCsvFile


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src/org/opencms/workplace/explorer/CmsNewCsvFile.java,v $
3  * Date : $Date: 2006/11/30 10:13:19 $
4  * Version: $Revision: 1.31 $
5  *
6  * This library is part of OpenCms -
7  * the Open Source Content Mananagement System
8  *
9  * Copyright (c) 2005 Alkacon Software GmbH (http://www.alkacon.com)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * For further information about Alkacon Software GmbH, please see the
22  * company website: http://www.alkacon.com
23  *
24  * For further information about OpenCms, please see the
25  * project website: http://www.opencms.org
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  */

31
32 package org.opencms.workplace.explorer;
33
34 import org.opencms.file.CmsProperty;
35 import org.opencms.file.CmsPropertyDefinition;
36 import org.opencms.file.CmsResource;
37 import org.opencms.file.CmsResourceFilter;
38 import org.opencms.file.types.CmsResourceTypePlain;
39 import org.opencms.i18n.CmsEncoder;
40 import org.opencms.jsp.CmsJspActionElement;
41 import org.opencms.main.CmsException;
42 import org.opencms.main.CmsLog;
43 import org.opencms.main.OpenCms;
44 import org.opencms.util.CmsStringUtil;
45 import org.opencms.util.CmsXsltUtil;
46 import org.opencms.workplace.CmsWorkplace;
47 import org.opencms.workplace.CmsWorkplaceException;
48
49 import java.util.ArrayList JavaDoc;
50 import java.util.Arrays JavaDoc;
51 import java.util.Collections JavaDoc;
52 import java.util.Iterator JavaDoc;
53 import java.util.List JavaDoc;
54
55 import javax.servlet.http.HttpServletRequest JavaDoc;
56 import javax.servlet.http.HttpServletResponse JavaDoc;
57 import javax.servlet.jsp.JspException JavaDoc;
58 import javax.servlet.jsp.PageContext JavaDoc;
59
60 import org.apache.commons.fileupload.FileItem;
61 import org.apache.commons.logging.Log;
62
63 /**
64  * The new resource upload dialog handles the upload of CSV (Comma Separated Values) files.<p>
65  *
66  * CSV files are converted in a first step to xml
67  * and in a second step transformed using a xsl stylesheet.<p>
68  *
69  * The following files use this class:
70  * <ul>
71  * <li>/commons/newcsvfile_upload.jsp
72  * </ul>
73  * <p>
74  *
75  * @author Jan Baudisch
76  *
77  * @version $Revision: 1.31 $
78  *
79  * @since 6.0.0
80  */

81 public class CmsNewCsvFile extends CmsNewResourceUpload {
82
83     /** Constant for automatically selecting the best fitting delimiter. */
84     public static final String JavaDoc BEST_DELIMITER = "best";
85
86     /** Constant for the height of the dialog frame. */
87     public static final String JavaDoc FRAMEHEIGHT = "450";
88
89     /** Request parameter name for the CSV content. */
90     public static final String JavaDoc PARAM_CSVCONTENT = "csvcontent";
91
92     /** Request parameter name for the delimiter. */
93     public static final String JavaDoc PARAM_DELIMITER = "delimiter";
94
95     /** Request parameter name for the XSLT file. */
96     public static final String JavaDoc PARAM_XSLTFILE = "xsltfile";
97
98     /** Constant for the xslt file suffix for table transformations. */
99     public static final String JavaDoc TABLE_XSLT_SUFFIX = ".table.xslt";
100
101     /** Constant for the tab-value inside delimiter the select. */
102     public static final String JavaDoc TABULATOR = "tab";
103
104     /** The log object for this class. */
105     private static final Log LOG = CmsLog.getLog(CmsNewCsvFile.class);
106
107     /** The pasted CSV content. */
108     private String JavaDoc m_paramCsvContent;
109
110     /** The delimiter to separate the CSV values. */
111     private String JavaDoc m_paramDelimiter;
112
113     /** The XSLT File to transform the table with. */
114     private String JavaDoc m_paramXsltFile;
115
116     /**
117      * Public constructor with JSP action element.<p>
118      *
119      * @param jsp an initialized JSP action element
120      */

121     public CmsNewCsvFile(CmsJspActionElement jsp) {
122
123         super(jsp);
124     }
125
126     /**
127      * Public constructor with JSP variables.<p>
128      *
129      * @param context the JSP page context
130      * @param req the JSP request
131      * @param res the JSP response
132      */

133     public CmsNewCsvFile(PageContext JavaDoc context, HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) {
134
135         this(new CmsJspActionElement(context, req, res));
136     }
137
138     /**
139      * Embeds the given content as cdata if neccessary.<p>
140      * Contents starting with "<" and ending with ">" are NOT embedded in order to allow content with tags.
141      *
142      * @param content the content
143      * @return the embedded content
144      */

145     static String JavaDoc toXmlBody(String JavaDoc content) {
146
147         StringBuffer JavaDoc xmlBody = new StringBuffer JavaDoc(1024);
148         content = content.trim();
149
150         if (content.startsWith("<") && content.endsWith(">")) {
151             return content;
152         } else {
153             xmlBody.append("<![CDATA[");
154             xmlBody.append(content);
155             xmlBody.append("]]>");
156         }
157
158         return xmlBody.toString();
159     }
160
161     /**
162      * Uploads the specified file and transforms it to HTML.<p>
163      *
164      * @throws JspException if inclusion of error dialog fails
165      */

166     public void actionUpload() throws JspException JavaDoc {
167
168         String JavaDoc newResname = "";
169
170         try {
171             if (CmsStringUtil.isNotEmpty(getParamCsvContent())) {
172                 // csv content is pasted in the textarea
173
newResname = "csvcontent.html";
174                 setParamNewResourceName("");
175             } else {
176                 setParamCsvContent(new String JavaDoc(getFileContentFromUpload(), CmsEncoder.ENCODING_ISO_8859_1));
177                 newResname = getCms().getRequestContext().getFileTranslator().translateResource(
178                     CmsResource.getName(getParamResource().replace('\\', '/')));
179                 newResname = CmsStringUtil.changeFileNameSuffixTo(newResname, "html");
180                 setParamNewResourceName(newResname);
181             }
182
183             setParamResource(newResname);
184             setParamResource(computeFullResourceName());
185             int resTypeId = OpenCms.getResourceManager().getDefaultTypeForName(newResname).getTypeId();
186
187             // transform csv to html
188
String JavaDoc xmlContent = CmsXsltUtil.transformCsvContent(
189                 getCms(),
190                 getParamXsltFile(),
191                 getParamCsvContent(),
192                 (BEST_DELIMITER.equals(getParamDelimiter()) ? null : getParamDelimiter()));
193             byte[] content = xmlContent.getBytes();
194
195             // if xslt file parameter is set, transform the raw html and set the css stylesheet property
196
// of the converted file to that of the stylesheet
197
CmsProperty styleProp = CmsProperty.getNullProperty();
198             if (CmsStringUtil.isNotEmpty(getParamXsltFile())) {
199                 styleProp = getCms().readPropertyObject(
200                     getParamXsltFile(),
201                     CmsPropertyDefinition.PROPERTY_STYLESHEET,
202                     true);
203             }
204
205             try {
206                 // create the resource
207
getCms().createResource(getParamResource(), resTypeId, content, Collections.EMPTY_LIST);
208             } catch (CmsException e) {
209                 // resource was present, overwrite it
210
getCms().lockResource(getParamResource());
211                 getCms().replaceResource(getParamResource(), resTypeId, content, null);
212             }
213             // copy xslt stylesheet-property to the new resource
214
if (!styleProp.isNullProperty()) {
215                 getCms().writePropertyObject(getParamResource(), styleProp);
216             }
217         } catch (Throwable JavaDoc e) {
218             // error uploading file, show error dialog
219
setParamMessage(Messages.get().getBundle(getLocale()).key(Messages.ERR_TABLE_IMPORT_FAILED_0));
220             includeErrorpage(this, e);
221         }
222     }
223
224     /**
225      * Builds a html select for Delimiters.
226      *
227      * @return html select code with the possible available xslt files
228      */

229     public String JavaDoc buildDelimiterSelect() {
230
231         Object JavaDoc[] optionStrings = new Object JavaDoc[] {
232             key(Messages.GUI_NEWRESOURCE_CONVERSION_DELIM_BEST_0),
233             key(Messages.GUI_NEWRESOURCE_CONVERSION_DELIM_SEMICOLON_0),
234             key(Messages.GUI_NEWRESOURCE_CONVERSION_DELIM_COMMA_0),
235             key(Messages.GUI_NEWRESOURCE_CONVERSION_DELIM_TAB_0)};
236         List JavaDoc options = new ArrayList JavaDoc(Arrays.asList(optionStrings));
237         List JavaDoc values = new ArrayList JavaDoc(Arrays.asList(new Object JavaDoc[] {"best", ";", ",", "tab"}));
238         String JavaDoc parameters = "name=\"" + PARAM_DELIMITER + "\" class=\"maxwidth\"";
239         return buildSelect(parameters, options, values, 0);
240     }
241
242     /**
243      * Builds a html select for the XSLT files.
244      *
245      * @return html select code with the possible available xslt files
246      */

247     public String JavaDoc buildXsltSelect() {
248
249         // read all xslt files
250
List JavaDoc xsltFiles = getXsltFiles();
251         if (xsltFiles.size() > 0) {
252             List JavaDoc options = new ArrayList JavaDoc();
253             List JavaDoc values = new ArrayList JavaDoc();
254
255             options.add(key(Messages.GUI_NEWRESOURCE_CONVERSION_NOSTYLE_0));
256             values.add("");
257
258             CmsResource resource;
259             CmsProperty titleProp = null;
260
261             Iterator JavaDoc i = xsltFiles.iterator();
262             while (i.hasNext()) {
263
264                 resource = (CmsResource)i.next();
265                 try {
266                     titleProp = getCms().readPropertyObject(
267                         resource.getRootPath(),
268                         CmsPropertyDefinition.PROPERTY_TITLE,
269                         false);
270                 } catch (CmsException e) {
271                     if (LOG.isWarnEnabled()) {
272                         LOG.warn(e);
273                     }
274                 }
275                 values.add(resource.getRootPath());
276                 // display the title if set or otherwise the filename
277
if (titleProp.isNullProperty()) {
278                     options.add("[" + resource.getName() + "]");
279                 } else {
280                     options.add(titleProp.getValue());
281                 }
282             }
283
284             StringBuffer JavaDoc result = new StringBuffer JavaDoc(512);
285             // build a select box and a table row around
286
result.append("<tr><td style=\"white-space: nowrap;\" unselectable=\"on\">");
287             result.append(key(Messages.GUI_NEWRESOURCE_CONVERSION_XSLTFILE_0));
288             result.append("</td><td class=\"maxwidth\">");
289             String JavaDoc parameters = "class=\"maxwidth\" name=\"" + PARAM_XSLTFILE + "\"";
290             result.append(buildSelect(parameters, options, values, 0));
291             result.append("</td><tr>");
292             return result.toString();
293         } else {
294             return "";
295         }
296     }
297
298     /**
299      * Returns the content of the file upload and sets the resource name.<p>
300      *
301      * @return the byte content of the uploaded file
302      * @throws CmsWorkplaceException if the filesize if greater that maxFileSizeBytes or if the upload file cannot be found
303      */

304     public byte[] getFileContentFromUpload() throws CmsWorkplaceException {
305
306         byte[] content;
307         // get the file item from the multipart request
308
Iterator JavaDoc i = getMultiPartFileItems().iterator();
309         FileItem fi = null;
310         while (i.hasNext()) {
311             fi = (FileItem)i.next();
312             if (fi.getName() != null) {
313                 // found the file object, leave iteration
314
break;
315             } else {
316                 // this is no file object, check next item
317
continue;
318             }
319         }
320
321         if (fi != null) {
322             long size = fi.getSize();
323             if (size == 0) {
324                 throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_UPLOAD_FILE_NOT_FOUND_0));
325             }
326             long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCms());
327             // check file size
328
if (maxFileSizeBytes > 0 && size > maxFileSizeBytes) {
329                 throw new CmsWorkplaceException(Messages.get().container(
330                     Messages.ERR_UPLOAD_FILE_SIZE_TOO_HIGH_1,
331                     new Long JavaDoc(maxFileSizeBytes / 1024)));
332             }
333             content = fi.get();
334             fi.delete();
335             setParamResource(fi.getName());
336
337         } else {
338             throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_UPLOAD_FILE_NOT_FOUND_0));
339         }
340         return content;
341     }
342
343     /**
344      * Returns the height of the head frameset.<p>
345      *
346      * @return the height of the head frameset
347      */

348     public String JavaDoc getHeadFrameSetHeight() {
349
350         return FRAMEHEIGHT;
351     }
352
353     /**
354      * Returns the pasted csv content.<p>
355      *
356      * @return the csv content
357      */

358     public String JavaDoc getParamCsvContent() {
359
360         return m_paramCsvContent;
361     }
362
363     /**
364      * Returns the delimiter to separate the CSV values.<p>
365      *
366      * @return the delimiter to separate the CSV values
367      */

368     public String JavaDoc getParamDelimiter() {
369
370         return m_paramDelimiter;
371     }
372
373     /**
374      * Returns the xslt file to transform the xml with.<p>
375      *
376      * @return the path to the xslt file to transform the xml with or null if it is not set
377      */

378     public String JavaDoc getParamXsltFile() {
379
380         return m_paramXsltFile;
381     }
382
383     /**
384      * Returns a list of CmsResources with the xslt files in the modules folder.<p>
385      *
386      * @return a list of the available xslt files
387      */

388     public List JavaDoc getXsltFiles() {
389
390         List JavaDoc result = new ArrayList JavaDoc();
391         try {
392             // find all files of generic xmlcontent in the modules folder
393
Iterator JavaDoc xmlFiles = getCms().readResources(
394                 CmsWorkplace.VFS_PATH_MODULES,
395                 CmsResourceFilter.DEFAULT_FILES.addRequireType(CmsResourceTypePlain.getStaticTypeId()),
396                 true).iterator();
397             while (xmlFiles.hasNext()) {
398                 CmsResource xmlFile = (CmsResource)xmlFiles.next();
399                 // filter all files with the suffix .table.xml
400
if (xmlFile.getName().endsWith(TABLE_XSLT_SUFFIX)) {
401                     result.add(xmlFile);
402                 }
403             }
404         } catch (CmsException e) {
405             LOG.error(e);
406         }
407         return result;
408
409     }
410
411     /**
412      * Sets the pasted csv content.<p>
413      *
414      * @param csvContent the csv content to set
415      */

416     public void setParamCsvContent(String JavaDoc csvContent) {
417
418         m_paramCsvContent = csvContent;
419     }
420
421     /**
422      * Sets the delimiter to separate the CSV values.<p>
423      *
424      * @param delimiter the delimiter to separate the CSV values.
425      */

426     public void setParamDelimiter(String JavaDoc delimiter) {
427
428         m_paramDelimiter = delimiter;
429     }
430
431     /**
432      * Sets the path to the xslt file.<p>
433      *
434      * @param xsltFile the file to transform the xml with.
435      */

436     public void setParamXsltFile(String JavaDoc xsltFile) {
437
438         m_paramXsltFile = xsltFile;
439     }
440 }
Popular Tags