KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > lenya > cms > cocoon > acting > UploadAction


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */

17
18 /* $Id: UploadAction.java 161890 2005-04-19 14:05:19Z edith $ */
19
20 package org.apache.lenya.cms.cocoon.acting;
21
22 import java.io.File JavaDoc;
23 import java.io.FileOutputStream JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.util.Collections JavaDoc;
27 import java.util.Enumeration JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.Map JavaDoc;
31
32 import javax.xml.parsers.ParserConfigurationException JavaDoc;
33 import javax.xml.transform.TransformerConfigurationException JavaDoc;
34 import javax.xml.transform.TransformerException JavaDoc;
35
36 import org.apache.avalon.excalibur.io.FileUtil;
37 import org.apache.avalon.framework.parameters.Parameters;
38 import org.apache.cocoon.acting.AbstractConfigurableAction;
39 import org.apache.cocoon.environment.ObjectModelHelper;
40 import org.apache.cocoon.environment.Redirector;
41 import org.apache.cocoon.environment.Request;
42 import org.apache.cocoon.environment.SourceResolver;
43 import org.apache.cocoon.servlet.multipart.Part;
44 import org.apache.lenya.cms.publication.Document;
45 import org.apache.lenya.cms.publication.PageEnvelope;
46 import org.apache.lenya.cms.publication.PageEnvelopeFactory;
47 import org.apache.lenya.cms.publication.ResourcesManager;
48 import org.apache.lenya.xml.DocumentHelper;
49 import org.apache.lenya.xml.NamespaceHelper;
50 import org.w3c.dom.Element JavaDoc;
51
52 /**
53  * The class <code>UploadAction</code> implements an action that allows for asset and content
54  * upload. An upload consists of a file upload plus optionally a file creation for the meta data of
55  * the asset.
56  *
57  * Also see org.apache.lenya.cms.authoring.UploadHelper
58  */

59 public class UploadAction extends AbstractConfigurableAction {
60
61     private Document document;
62     private PageEnvelope pageEnvelope;
63
64     public static final String JavaDoc UPLOADASSET_PARAM_NAME = "properties.asset.data";
65     public static final String JavaDoc UPLOADASSET_PARAM_PREFIX = "properties.asset.";
66
67     public static final String JavaDoc UPLOADASSET_RETURN_FILESIZE = "file-size";
68     public static final String JavaDoc UPLOADASSET_RETURN_MIMETYPE = "mime-type";
69
70     public static final String JavaDoc CONTENT_PREFIX = "content";
71
72     public static final String JavaDoc FILE_NAME_REGEXP = "[-a-zA-Z0-9_.]+";
73
74     // optional parameters for meta data according to dublin core
75
public static final String JavaDoc[] DUBLIN_CORE_PARAMETERS = { "title", "creator", "subject",
76             "description", "publisher", "contributor", "date", "type", "format", "identifier",
77             "source", "language", "relation", "coverage", "rights" };
78
79     /**
80      * Retrieve the file from the request and store it in the corresponding directory, optionally
81      * create a meta file and optionally insert an image tag in the requesting document.
82      *
83      * @param redirector a <code>Redirector</code> value
84      * @param resolver a <code>SourceResolver</code> value
85      * @param objectModel a <code>Map</code> value
86      * @param source a <code>String</code> value
87      * @param parameters a <code>Parameters</code> value
88      *
89      * @return a <code>Map</code> containing the referer or null if the name of the file to be
90      * uploaded contains characters that are not allowed (@see FILE_NAME_REGEXP).
91      *
92      * @exception Exception if an error occurs
93      */

94     public Map JavaDoc act(Redirector redirector, SourceResolver resolver, Map JavaDoc objectModel, String JavaDoc source,
95             Parameters parameters) throws Exception JavaDoc {
96
97         Map JavaDoc results = new HashMap JavaDoc();
98         Request request = ObjectModelHelper.getRequest(objectModel);
99         pageEnvelope = PageEnvelopeFactory.getInstance().getPageEnvelope(objectModel);
100         document = pageEnvelope.getDocument();
101
102         File JavaDoc assetFile;
103
104         logRequestParameters(request);
105
106         // determine if the upload is an asset or a content upload
107
String JavaDoc uploadType = request.getParameter("uploadtype");
108
109         // make asset upload the default if it is not specified
110
if (uploadType == null) {
111             uploadType = "asset";
112         }
113
114         Map JavaDoc dublinCoreParams = getDublinCoreParameters(request);
115
116         // upload the file to the uploadDir
117
Part part = (Part) request.get(UPLOADASSET_PARAM_NAME);
118
119         String JavaDoc fileName = part.getFileName();
120         if (!fileName.matches(FILE_NAME_REGEXP) || FileUtil.getExtension(fileName).equals("")) {
121             // the file name contains characters which mean trouble
122
// and are therefore not allowed.
123
getLogger().warn("The filename [" + fileName + "] is not valid for an asset.");
124             return null;
125         }
126         // convert spaces in the file name to underscores
127
fileName = fileName.replace(' ', '_');
128         String JavaDoc mimeType = part.getMimeType();
129         int fileSize = part.getSize();
130
131         results.put(UPLOADASSET_RETURN_MIMETYPE, mimeType);
132         results.put(UPLOADASSET_RETURN_FILESIZE, new Integer JavaDoc(fileSize));
133
134         dublinCoreParams.put("format", mimeType);
135         dublinCoreParams.put("extent", Integer.toString(fileSize));
136
137         if (uploadType.equals("asset")) {
138             ResourcesManager resourcesMgr = new ResourcesManager(document);
139             assetFile = new File JavaDoc(resourcesMgr.getPath(), fileName);
140
141             if (!resourcesMgr.getPath().exists()) {
142                 resourcesMgr.getPath().mkdirs();
143             }
144
145             // create an extra file containing the meta description for
146
// the asset.
147
File JavaDoc metaDataFile = new File JavaDoc(resourcesMgr.getPath(), fileName + ".meta");
148             createMetaData(metaDataFile, dublinCoreParams);
149
150         }
151         // must be a content upload then
152
else {
153             assetFile = new File JavaDoc(document.getFile().getParent(), fileName);
154             getLogger().debug("assetFile: " + assetFile);
155         }
156
157         saveAsset(assetFile, part);
158
159         return Collections.unmodifiableMap(results);
160     }
161
162     /**
163      * Saves the asset to a file.
164      *
165      * @param assetFile The asset file.
166      * @param part The part of the multipart request.
167      * @throws Exception if an error occurs.
168      */

169     protected void saveAsset(File JavaDoc assetFile, Part part) throws Exception JavaDoc {
170         if (!assetFile.exists()) {
171             boolean created = assetFile.createNewFile();
172             if (!created) {
173                 throw new RuntimeException JavaDoc("The file [" + assetFile + "] could not be created.");
174             }
175     }
176
177         byte[] buf = new byte[4096];
178         FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(assetFile);
179         try {
180             InputStream JavaDoc in = part.getInputStream();
181             int read = in.read(buf);
182
183             while (read > 0) {
184                 out.write(buf, 0, read);
185                 read = in.read(buf);
186             }
187         } finally {
188             out.close();
189         }
190     }
191
192     /**
193      * Logs the request parameters.
194      * @param request The request.
195      */

196     protected void logRequestParameters(Request request) {
197         for (Enumeration JavaDoc myenum = request.getParameterNames(); myenum.hasMoreElements();) {
198             String JavaDoc param = (String JavaDoc) myenum.nextElement();
199             getLogger().debug(
200                     param + ": " + request.getParameter(param) + " [" + request.get(param) + "]");
201         }
202     }
203
204     /**
205      * Retrieves optional parameters for the meta file which contains dublin core information from
206      * the request.
207      * @param request The request.
208      * @return A map.
209      */

210     protected Map JavaDoc getDublinCoreParameters(Request request) {
211         HashMap JavaDoc dublinCoreParams = new HashMap JavaDoc();
212
213         for (int i = 0; i < DUBLIN_CORE_PARAMETERS.length; i++) {
214             String JavaDoc paramName = DUBLIN_CORE_PARAMETERS[i];
215             String JavaDoc paramValue = request.getParameter(UPLOADASSET_PARAM_PREFIX + paramName);
216
217             if (paramValue == null) {
218                 paramValue = "";
219             }
220
221             dublinCoreParams.put(paramName, paramValue);
222         }
223         
224         Iterator JavaDoc iter = dublinCoreParams.keySet().iterator();
225         while (iter.hasNext()) {
226             String JavaDoc paramName = (String JavaDoc) iter.next();
227             getLogger().debug(paramName + ": " + dublinCoreParams.get(paramName));
228         }
229         
230         return dublinCoreParams;
231     }
232
233     /**
234      * Create the meta data file given the dublin core parameters.
235      *
236      * @param metaDataFile the file where the meta data file is to be created
237      * @param dublinCoreParams a <code>Map</code> containing the dublin core values
238      * @throws TransformerConfigurationException if an error occurs.
239      * @throws TransformerException if an error occurs.
240      * @throws IOException if an error occurs
241      * @throws ParserConfigurationException if an error occurs.
242      */

243     protected void createMetaData(File JavaDoc metaDataFile, Map JavaDoc dublinCoreParams)
244             throws TransformerConfigurationException JavaDoc, TransformerException JavaDoc, IOException JavaDoc,
245             ParserConfigurationException JavaDoc {
246
247         assert (metaDataFile.getParentFile().exists());
248
249         NamespaceHelper helper = new NamespaceHelper("http://purl.org/dc/elements/1.1/", "dc",
250                 "metadata");
251
252         Element JavaDoc root = helper.getDocument().getDocumentElement();
253
254         Iterator JavaDoc iter = dublinCoreParams.keySet().iterator();
255
256         while (iter.hasNext()) {
257             String JavaDoc tagName = (String JavaDoc) iter.next();
258             String JavaDoc tagValue = (String JavaDoc) dublinCoreParams.get(tagName);
259             root.appendChild(helper.createElement(tagName, tagValue));
260         }
261
262         DocumentHelper.writeDocument(helper.getDocument(), metaDataFile);
263     }
264 }
Popular Tags