KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > fields > ContentFileField


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12

13 package org.jahia.services.fields;
14
15 import org.jahia.data.ConnectionTypes;
16 import org.jahia.data.files.JahiaFileField;
17 import org.jahia.exceptions.JahiaException;
18 import org.jahia.params.ParamBean;
19 import org.jahia.registries.ServicesRegistry;
20 import org.jahia.services.filemanager.Filemanager;
21 import org.jahia.services.filemanager.JahiaFileFieldsManager;
22 import org.jahia.services.filemanager.JahiaFilemanagerService;
23 import org.jahia.services.version.*;
24 import org.jahia.services.webdav.DAVFileAccess;
25 import org.jahia.services.webdav.JahiaWebdavBaseService;
26 import org.jahia.utils.Base64;
27 import org.jahia.utils.xml.XMLSerializationOptions;
28 import org.jahia.utils.xml.XmlWriter;
29
30 import java.io.*;
31 import java.util.Hashtable JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Set JavaDoc;
34 import java.util.Vector JavaDoc;
35
36
37 public class ContentFileField extends ContentField {
38     private static org.apache.log4j.Logger logger =
39             org.apache.log4j.Logger.getLogger (ContentFileField.class);
40
41     protected ContentFileField (Integer JavaDoc ID,
42                                 Integer JavaDoc jahiaID,
43                                 Integer JavaDoc pageID,
44                                 Integer JavaDoc ctnid,
45                                 Integer JavaDoc fieldDefID,
46                                 Integer JavaDoc fieldType,
47                                 Integer JavaDoc connectType,
48                                 Integer JavaDoc aclID,
49                                 Vector JavaDoc activeAndStagingEntryStates,
50                                 Hashtable JavaDoc activeAndStagedDBValues) {
51         super (ID.intValue (), jahiaID.intValue (), pageID.intValue (),
52                 ctnid.intValue (), fieldDefID.intValue (), fieldType.intValue (),
53                 connectType.intValue (), aclID.intValue (), activeAndStagingEntryStates,
54                 activeAndStagedDBValues);
55     }
56
57
58     public static synchronized ContentFileField createFile (int siteID,
59                                                             int pageID, int containerID,
60                                                             int fieldDefID, int parentAclID,
61                                                             int aclID,
62                                                             JahiaFileField fField,
63                                                             ParamBean jParams)
64             throws JahiaException {
65         ContentFileField result =
66                 (ContentFileField) ContentField.createField (siteID, pageID,
67                         containerID, fieldDefID,
68                         ContentFieldTypes.FILE,
69                         ConnectionTypes.LOCAL,
70                         parentAclID, aclID);
71
72         EntrySaveRequest saveRequest =
73                 new EntrySaveRequest (jParams.getUser (),
74                         jParams.getLocale ().toString ());
75
76         result.setFile (fField, saveRequest);
77         return result;
78     }
79
80     //--------------------------------------------------------------------------
81
/**
82      * Gets the String representation of this field. In case of an Application,
83      * it will be the output of the application, in case of a bigtext it will
84      * be the full content of the bigtext, etc. This is called by the public
85      * method getValue of ContentField, which does the entryState resolving
86      * This method should call getDBValue to get the DBValue
87      */

88     public String JavaDoc getValue (ParamBean jParams,
89                                ContentObjectEntryState entryState)
90             throws JahiaException {
91         return getDBValue (entryState);
92     }
93
94     //--------------------------------------------------------------------------
95
/**
96      * This method should call preSet and postSet.
97      */

98     public void setFile (JahiaFileField fField, EntrySaveRequest saveRequest)
99             throws JahiaException {
100         if (fField == null) {
101             return;
102         }
103 // preSet (String.valueOf(fField.getID()), saveRequest);
104
preSet (fField.getRealName (), saveRequest);
105     }
106
107     //--------------------------------------------------------------------------
108
/**
109      * get the Value that will be added to the search engine for this field.
110      * for a bigtext it will be the content of the bigtext, for an application
111      * the string will be empty!
112      * Do not return null, return an empty string instead.
113      *
114      * @param jParams the jParam containing the loadVersion and locales
115      */

116     public String JavaDoc getValueForSearch (ParamBean jParams,
117                                      ContentObjectEntryState entryState)
118             throws JahiaException {
119         return getDBValue (entryState);
120     }
121
122     //--------------------------------------------------------------------------
123
/**
124      * This method is called when there is a workflow state change
125      * Such as staged mode -> active mode (validation), active -> inactive (for versioning)
126      * and also staged mode -> other staged mode (workflow)
127      * This method should not write/change the DBValue, the service handles that.
128      *
129      * @param fromEntryState the entry state that is currently was in the database
130      * @param toEntryState the entry state that will be written to the database
131      * @param jParams ParamBean object used to get information about the user
132      * doing the request, the current locale, etc...
133      *
134      * @return null if the entry state change wasn't an activation, otherwise it
135      * returns an object that contains the status of the activation (whether
136      * successfull, partial or failed, as well as messages describing the
137      * warnings during the activation process)
138      */

139     public ActivationTestResults changeEntryState (ContentObjectEntryState fromEntryState,
140                                                    ContentObjectEntryState toEntryState,
141                                                    ParamBean jParams,
142                                                    StateModificationContext stateModifContext)
143             throws JahiaException {
144         DAVFileAccess file = JahiaWebdavBaseService.getInstance ().getDAVFileAccess (jParams,
145                 this.getValue (fromEntryState));
146
147         if (file.isValid () && file.hasRevisions ()) {
148 // String fieldPrefix = getID()+";";
149
List JavaDoc usages = JahiaWebdavBaseService.getInstance ().findUsages (file.getPath (),
150                     jParams, true);
151 // String list = (String) file.getProperty("http://www.jahia.org/", "publishedfieldsinuse");
152
boolean wasLocked = fromEntryState.getWorkflowState () == EntryLoadRequest.ACTIVE_WORKFLOW_STATE || fromEntryState.getWorkflowState () == EntryLoadRequest.WAITING_WORKFLOW_STATE;
153             boolean wasUnlocked = fromEntryState.getWorkflowState () != EntryLoadRequest.ACTIVE_WORKFLOW_STATE && fromEntryState.getWorkflowState () != EntryLoadRequest.WAITING_WORKFLOW_STATE;
154             boolean shouldBeLocked = toEntryState.getWorkflowState () == EntryLoadRequest.ACTIVE_WORKFLOW_STATE || toEntryState.getWorkflowState () == EntryLoadRequest.WAITING_WORKFLOW_STATE;
155             boolean shouldBeUnlocked = toEntryState.getWorkflowState () != EntryLoadRequest.ACTIVE_WORKFLOW_STATE && toEntryState.getWorkflowState () != EntryLoadRequest.WAITING_WORKFLOW_STATE;
156             if (wasLocked && shouldBeUnlocked) {
157 // if (list == null) {
158
// list = "";
159
// }
160
// if (list.startsWith(fieldPrefix)) {
161
// list = list.substring(fieldPrefix.length());
162
// } else if (list.indexOf(";"+fieldPrefix)>0) {
163
// list = list.substring(0,list.indexOf(";"+fieldPrefix))+ list.substring(list.indexOf(";"+fieldPrefix)+fieldPrefix.length());
164
// }
165
// if (list.length()==0) {
166
if (usages.size () == 1) {
167                     file.unlockFile (true);
168                 }
169 // }
170
// file.setProperty("http://www.jahia.org/", "publishedfieldsinuse", list, true);
171
} else if (wasUnlocked && shouldBeLocked && jParams.settings().isFileLockOnPublication()) {
172 // if (list == null) {
173
// list = "";
174
// }
175
// if (list.length()==0) {
176
if (usages.size () == 0) {
177                     file.unlockFile (true);
178                     file.lockFile (true);
179                 }
180 // }
181
// if (!list.startsWith(fieldPrefix) && list.indexOf(";"+fieldPrefix)==-1) {
182
// file.setProperty("http://www.jahia.org/", "publishedfieldsinuse", list + fieldPrefix, true);
183
// }
184
}
185         }
186
187
188         return new ActivationTestResults ();
189     }
190
191     //--------------------------------------------------------------------------
192
protected ActivationTestResults isContentValidForActivation (
193             Set JavaDoc languageCodes,
194             ParamBean jParams,
195             StateModificationContext stateModifContext)
196             throws JahiaException {
197         /** @todo to be implemented */
198         return new ActivationTestResults ();
199     }
200
201     //--------------------------------------------------------------------------
202
/**
203      * This method is called when a entry should be copied into a new entry
204      * it is called when an old version -> active version move occurs
205      * This method should not write/change the DBValue, the service handles that.
206      *
207      * @param fromEntryState the entry state that is currently was in the database
208      * @param toEntryState the entry state that will be written to the database
209      */

210     public void copyEntry (EntryStateable fromEntryState,
211                            EntryStateable toEntryState)
212             throws JahiaException {
213
214         super.copyEntry (fromEntryState, toEntryState);
215
216         if ((toEntryState.getWorkflowState ()
217                 == EntryLoadRequest.STAGING_WORKFLOW_STATE)
218                 && (fromEntryState.getWorkflowState ()
219                 != EntryLoadRequest.STAGING_WORKFLOW_STATE)) {
220
221             String JavaDoc fromValue = this.getDBValue (fromEntryState);
222             try {
223                 JahiaFileField fField = JahiaFileFieldsManager.getInstance ()
224                         .getJahiaFileField (Integer.parseInt (fromValue));
225                 // force to recreate a new entry
226
fField.setID (-1);
227                 JahiaFileFieldsManager.getInstance ().insertJahiaFileField (fField);
228                 EntrySaveRequest saveRequest =
229                         new EntrySaveRequest (fromEntryState.getLanguageCode ());
230                 this.setFile (fField, saveRequest);
231             } catch (java.lang.NumberFormatException JavaDoc nfe) {
232                 logger.debug (
233                         "File Field number format exception when parsing from field value[" + this.getID () + "], fieldvalue=" + fromValue);
234             } catch (Throwable JavaDoc t) {
235                 logger.debug ("copyEntry for field[" + this.getID () + "] exception", t);
236             }
237         }
238     }
239
240     //--------------------------------------------------------------------------
241
/**
242      * This method is called when an entry should be deleted for real.
243      * It is called when a field is deleted, and versioning is disabled, or
244      * when staging values are undone.
245      * For a bigtext for instance, this method should delete the text file
246      * corresponding to this field entry
247      *
248      * @param deleteEntryState the entry state to delete
249      */

250     public void deleteEntry (EntryStateable deleteEntryState)
251             throws JahiaException {
252         /** @todo to be implemented */
253         super.deleteEntry (deleteEntryState);
254     }
255
256     //--------------------------------------------------------------------------
257
/**
258      * Is this kind of field shared (i.e. not one version for each language,
259      * but one version for every language)
260      */

261     public boolean isShared () {
262         return false;
263     }
264
265     /**
266      * This is called on all content fields to have them serialized only their
267      * specific part. The actual field metadata seriliazing is handled by the
268      * ContentField class. This method is called multiple times per field
269      * according to the workflow state, languages and versioning entries we
270      * want to serialize.
271      *
272      * @param xmlWriter the XML writer object in which to write the XML output
273      * @param xmlSerializationOptions options used to activate/bypass certain
274      * output of elements.
275      * @param entryState the ContentFieldEntryState for which to generate the
276      * XML export.
277      * @param paramBean specifies context of serialization, such as current
278      * user, current request parameters, entry load request, URL generation
279      * information such as ServerName, ServerPort, ContextPath, etc... URL
280      * generation is an important part of XML serialization and this is why
281      * we pass this parameter down, as well as user rights checking.
282      *
283      * @throws IOException in case there was an error writing to the Writer
284      * output object.
285      */

286     protected void serializeContentToXML (XmlWriter xmlWriter,
287                                           XMLSerializationOptions xmlSerializationOptions,
288                                           ContentObjectEntryState entryState,
289                                           ParamBean paramBean) throws java.io.IOException JavaDoc {
290
291         try {
292             int fileID = -1;
293             try {
294                 fileID = Integer.parseInt (getDBValue (entryState));
295             } catch (Throwable JavaDoc t) {
296                 // this can fail if we are using a default value or if we
297
// have a reference to a WebDAV file field
298
}
299
300             JahiaFilemanagerService fMgr = ServicesRegistry.getInstance ()
301                     .getJahiaFilemanagerService ();
302             JahiaFileField fileField = JahiaWebdavBaseService.getInstance ().getJahiaFileField (
303                     paramBean, getDBValue (entryState));
304             // JahiaFileField fileField = JahiaFileFieldsManager.getInstance().getJahiaFileField(fileID);
305
Filemanager fmng = fMgr.getFilemanager (fileField.getFilemanagerID ());
306
307             if (xmlSerializationOptions.isEmbeddingBinary ()) {
308
309                 // we want to embed the full file binary information directly
310
// into the XML stream.
311

312                 xmlWriter.writeEntity ("file").
313                         writeAttribute ("name", fileField.getRealName ()).
314                         writeAttribute ("contentType", fileField.getType ()).
315                         writeAttribute ("encoding", "base64");
316
317                 String JavaDoc path = fMgr.getFileRepositoryRootPath () + File.separator +
318                         fmng.getStoragePath () + File.separator +
319                         fileField.getStorageName ();
320
321                 FileInputStream fileStream = new FileInputStream (path);
322                 ByteArrayOutputStream byteArray = new ByteArrayOutputStream ();
323                 copyStream (fileStream, byteArray, 65536);
324                 char[] encodedStream = Base64.encode (byteArray.toByteArray ());
325                 StringBuffer JavaDoc result = new StringBuffer JavaDoc (encodedStream.length);
326                 result.append ("\n");
327                 for (int i = 0; i < encodedStream.length; i++) {
328                     result.append (encodedStream[i]);
329                     if (i % 76 == 75) {
330                         result.append ("\n");
331                     }
332                 }
333                 result.append ("\n");
334                 xmlWriter.writeText (result.toString ());
335                 xmlWriter.endEntity ();
336             } else {
337                 // let's only build a reference to the file's content, using an
338
// URL to download the file's content :
339

340                 JahiaFileField jahiaFileField = JahiaWebdavBaseService.getInstance ()
341                         .getJahiaFileField (paramBean, getDBValue (entryState));
342                 if (jahiaFileField == null) {
343                     // we are in the case of a default value file.
344
xmlWriter.writeEntity ("file").
345                             writeAttribute ("url", getDBValue (entryState));
346                     xmlWriter.endEntity ();
347                 }
348
349                 xmlWriter.writeEntity ("file").
350                         writeAttribute ("url", jahiaFileField.getDownloadUrl ());
351                 xmlWriter.endEntity ();
352             }
353
354         } catch (JahiaException je) {
355             logger.debug ("Error while serializing file field to XML :", je);
356         }
357     }
358
359     /**
360      * Method copyStream<br>
361      *
362      * @param ins An InputStream.
363      * @param outs An OutputStream.
364      * @param bufferSize an integer specifying the buffer size to use to speed
365      * up operations.
366      *
367      * @throws IOException.
368      */

369     private void copyStream (InputStream ins,
370                              OutputStream outs, int bufferSize)
371             throws IOException {
372         byte[] m_WriteBuffer = new byte[bufferSize];
373         BufferedInputStream bis =
374                 new BufferedInputStream (ins, bufferSize);
375         BufferedOutputStream bos =
376                 new BufferedOutputStream (outs, bufferSize);
377         int bufread;
378         while ((bufread = bis.read (m_WriteBuffer)) != -1) {
379             bos.write (m_WriteBuffer, 0, bufread);
380         }
381         bos.flush ();
382         bos.close ();
383         bis.close ();
384         //outs.close();
385
}
386
387     protected void purgeContent ()
388             throws JahiaException {
389         /** @todo FIXME : to be implemented. */
390     }
391
392
393 }
394
Popular Tags