KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > dotmarketing > portlets > languagesmanager > action > EditLanguageManagerAction


1 /*
2  * Created on Sep 23, 2004
3  *
4  * TODO To change the template for this generated file go to
5  * Window - Preferences - Java - Code Style - Code Templates
6  */

7 package com.dotmarketing.portlets.languagesmanager.action;
8
9 import java.io.BufferedInputStream JavaDoc;
10 import java.io.File JavaDoc;
11 import java.io.FileInputStream JavaDoc;
12 import java.io.FileOutputStream JavaDoc;
13 import java.io.IOException JavaDoc;
14 import java.nio.channels.FileChannel JavaDoc;
15 import java.nio.channels.NonWritableChannelException JavaDoc;
16 import java.util.ArrayList JavaDoc;
17 import java.util.Enumeration JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.List JavaDoc;
20 import java.util.Properties JavaDoc;
21 import java.util.Set JavaDoc;
22 import java.util.TreeMap JavaDoc;
23 import javax.portlet.ActionRequest;
24 import javax.portlet.ActionResponse;
25 import javax.portlet.PortletConfig;
26 import org.apache.commons.logging.LogFactory;
27 import org.apache.struts.action.ActionForm;
28 import org.apache.struts.action.ActionMapping;
29 import com.dotmarketing.comparators.LanguageManagerComparator;
30 import com.dotmarketing.portal.struts.DotPortletAction;
31 import com.dotmarketing.portlets.languagesmanager.factories.LanguageFactory;
32 import com.dotmarketing.portlets.languagesmanager.model.Language;
33 import com.dotmarketing.util.Config;
34 import com.dotmarketing.util.Logger;
35 import com.dotmarketing.util.UtilMethods;
36 import com.dotmarketing.util.WebKeys;
37 import com.liferay.portal.model.User;
38 import com.liferay.portal.util.Constants;
39 import com.liferay.util.servlet.SessionMessages;
40
41
42 /**
43  * @author alex
44  */

45 public class EditLanguageManagerAction extends DotPortletAction {
46     public void processAction(ActionMapping mapping, ActionForm form, PortletConfig config, ActionRequest req,
47         ActionResponse res) throws Exception JavaDoc {
48         String JavaDoc cmd = req.getParameter(Constants.CMD);
49
50         User user = _getUser(req);
51
52         //get list of languages
53
try {
54             _retrieveLanguage(req, res, config, form);
55         } catch (Exception JavaDoc e) {
56             _handleException(e, req);
57         }
58
59         // create if necesary and copy from normal files to tmp files
60
_checkLanguagesFiles(req, res, config, form);
61         
62         // re-copy from normal files to tmp files
63
if ((cmd != null) && cmd.equals("reset")) {
64             _resetLanguages(req, res, config, form);
65         }
66
67         /* load up from tmp files */
68         _retrieveProperties(req, res, config, form);
69
70         //write any changes and additions to tmp files and properties attribute
71
// remove any deleted rows
72
String JavaDoc hiddenkey = req.getParameter("hiddenkey");
73
74         if (hiddenkey != null) {
75             if (!(hiddenkey.equals(""))) {
76                 _deleteLanguageRow(req, res, config, form, user);
77             }
78         }
79         String JavaDoc languageId = req.getParameter("languageId");
80
81         if (languageId != null) {
82             if (!(languageId.equals(""))) {
83                 _deleteLanguage(req, res, config, form, languageId);
84             }
85         }
86         
87         if ((cmd != null) && (cmd.equals(Constants.ADD) )) {
88             try {
89                 _add(req, res, config, form);
90             } catch (Exception JavaDoc ae) {
91                 _handleException(ae, req);
92             }
93         } else if ((cmd != null) && cmd.equals(Constants.SAVE)) {
94             try {
95                 _add(req, res, config, form);
96                 _save(req, res, config, form);
97             } catch (Exception JavaDoc ae) {
98                 _handleException(ae, req);
99             }
100
101             _sendToReferral(req, res, "");
102         }
103
104         //filter results
105
_filterByKey(req, res, config, form);
106
107         //sort results
108
_sortProperties(req);
109         //paginate results
110
_paginateResults(req);
111         
112         
113        
114         setForward(req, "portlet.ext.languagesmanager.edit_languagesmanager");
115     }
116
117     
118     
119     
120     
121     
122     
123     
124     private void _deleteLanguage(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, String JavaDoc languageId) throws Exception JavaDoc {
125         Language language = LanguageFactory.getLanguage(languageId);
126         LanguageFactory.deleteLanguage(language);
127     }
128
129     private void _retrieveLanguage(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form)
130         throws Exception JavaDoc {
131         List JavaDoc list = null; // LinkedList();
132

133         if (req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST) == null) {
134             list = LanguageFactory.getLanguages();
135         } else {
136             list = (List JavaDoc) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST);
137         }
138
139         req.setAttribute(WebKeys.LANGUAGE_MANAGER_LIST, list);
140     }
141
142     /* copy the files into a temps files */
143     private void _resetLanguages(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form)
144         throws Exception JavaDoc {
145         List JavaDoc list = (List JavaDoc) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST);
146
147         for (int i = 0; i < list.size(); i++) {
148             long langId = ((Language) list.get(i)).getId();
149             try {
150                 String JavaDoc filePath = getGlobalVariablesPath()+"cms_language_" +
151                         langId + ".properties";
152
153                 // Create empty file
154
File JavaDoc from = new java.io.File JavaDoc(filePath);
155                 from.createNewFile();
156
157                 String JavaDoc tmpFilePath = getTemporyDirPath()+"cms_language_" +
158                 langId + "_properties.tmp";
159
160                 File JavaDoc to = new java.io.File JavaDoc(tmpFilePath);
161                 to.createNewFile();
162                
163                 FileChannel JavaDoc srcChannel = new FileInputStream JavaDoc(from).getChannel();
164
165                 // Create channel on the destination
166
FileChannel JavaDoc dstChannel = new FileOutputStream JavaDoc(to).getChannel();
167
168                 // Copy file contents from source to destination
169
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
170
171                 // Close the channels
172
srcChannel.close();
173                 dstChannel.close();
174                 
175             } catch (IOException JavaDoc e) {
176                 Logger.debug(this, "Property File copy Failed " + e, e);
177             }
178         }
179     }
180
181     /* check for the existence of the languages resource files, if not create that */
182     private void _checkLanguagesFiles(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form)
183         throws Exception JavaDoc {
184         List JavaDoc list = (List JavaDoc) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST);
185
186         for (int i = 0; i < list.size(); i++) {
187             long langId = ((Language) list.get(i)).getId();
188             try {
189                 String JavaDoc filePath = getGlobalVariablesPath()+"cms_language_" + langId + ".properties";
190
191                 boolean copy = false;
192                 
193                 // Create empty file
194
File JavaDoc from = new java.io.File JavaDoc(filePath);
195                 if (!from.exists()) {
196                     from.createNewFile();
197                     copy = true;
198                 }
199
200                 String JavaDoc tmpFilePath = getTemporyDirPath()+"cms_language_" + langId + "_properties.tmp";
201                 File JavaDoc to = new java.io.File JavaDoc(tmpFilePath);
202                 if (!to.exists()) {
203                     to.createNewFile();
204                     copy = true;
205                 }
206                
207                 if (copy) {
208                     FileChannel JavaDoc srcChannel = new FileInputStream JavaDoc(from).getChannel();
209                     // Create channel on the destination
210
FileChannel JavaDoc dstChannel = new FileOutputStream JavaDoc(to).getChannel();
211                     // Copy file contents from source to destination
212
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
213                     // Close the channels
214
srcChannel.close();
215                     dstChannel.close();
216                 }
217                 
218             } catch (IOException JavaDoc e) {
219                 Logger.error(this, "_checkLanguagesFiles:Property File Copy Failed " + e, e);
220             }
221         }
222     }
223     /* here we load up from the tmp files */
224     private void _retrieveProperties(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form)
225         throws Exception JavaDoc {
226         long time = System.currentTimeMillis();
227         List JavaDoc list = (List JavaDoc) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST);
228
229         Properties JavaDoc[] properties = new Properties JavaDoc[list.size()];
230
231         for (int i = 0; i < list.size(); i++) {
232             long langId = ((Language) list.get(i)).getId();
233             ClassLoader JavaDoc classLoader = getClass().getClassLoader();
234             try {
235                 //Loading properties file
236

237                 String JavaDoc filePath = getTemporyDirPath()+"cms_language_" +
238                         langId + "_properties.tmp";
239                 BufferedInputStream JavaDoc is = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(filePath));
240                 
241                 LogFactory.getLog(this.getClass()).debug("ClassLoader: " + is);
242                 if (is != null) {
243                     properties[i] = new Properties JavaDoc();
244                     properties[i].load(is);
245
246                     LogFactory.getLog(this.getClass()).debug("has: " + properties[i].size() + " keys");
247                 } else {
248                     properties[i] = new Properties JavaDoc();
249                 }
250                 is.close();
251             } catch (Exception JavaDoc e) {
252                 Logger.error(this, "Could not load this file =" + "cms_language_" + langId + "_properties.tmp", e);
253             }
254         }
255
256         req.setAttribute(WebKeys.LANGUAGE_MANAGER_PROPERTIES, properties);
257     }
258
259     private void _deleteLanguageRow(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form,
260         User user) throws Exception JavaDoc {
261         List JavaDoc list = (List JavaDoc) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST);
262         Properties JavaDoc[] properties = (Properties JavaDoc[]) req.getAttribute(WebKeys.LANGUAGE_MANAGER_PROPERTIES);
263         String JavaDoc key = req.getParameter("hiddenkey");
264
265         for (int i = 0; i < list.size(); i++) {
266             long langId = ((Language) list.get(i)).getId();
267             properties[i].remove(key);
268
269             properties[i].store(new java.io.FileOutputStream JavaDoc(getTemporyDirPath()+
270                     "cms_language_" + langId + "_properties.tmp"), null);
271         }
272
273         req.setAttribute(WebKeys.LANGUAGE_MANAGER_PROPERTIES, properties);
274         SessionMessages.add(req, "message", "message.languagemanager.delete");
275     }
276
277     private void _add(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form)
278         throws Exception JavaDoc {
279         int number = 0;
280
281         try {
282             number = Integer.parseInt(req.getParameter("number"));
283         } catch (Exception JavaDoc e) {
284             return;
285         }
286
287         List JavaDoc list = (List JavaDoc) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST);
288
289         Properties JavaDoc[] properties = (Properties JavaDoc[]) req.getAttribute(WebKeys.LANGUAGE_MANAGER_PROPERTIES);
290         boolean changed = false;
291
292         for (int i = 0; i < list.size(); i++) {
293             for (int j = 0; j <= number; j++) {
294                 String JavaDoc lang_code = ((Language) list.get(i)).getLanguageCode();
295                 String JavaDoc key = req.getParameter("key" + j);
296                 String JavaDoc value = req.getParameter("value" + j + "," + lang_code);
297                 String JavaDoc valueFirst = req.getParameter("value" + j + ",en"); //this
298
// is
299
// only
300
// to
301
// check
302
// that
303
// the
304
// keep
305
// the
306
// properties
307
// english
308
// file
309
// like
310
// the
311

312                 /*
313                  * if(j == number){ addedKey = req.getParameter("key"+j); }
314                  */

315                 try {
316                     if (properties[i] == null) {
317                         changed = true;
318                         properties[i] = new Properties JavaDoc();
319                     }
320
321                     if ((!key.equals("")) && (!valueFirst.equals(""))) {
322                         changed = true;
323                         properties[i].setProperty(key, value);
324                     }
325                 } catch (Exception JavaDoc e) {
326                 }
327
328                 if (changed) {
329                     long langId = ((Language) list.get(i)).getId();
330
331                     properties[i].store(new java.io.FileOutputStream JavaDoc(getTemporyDirPath()+"cms_language_" +
332                             langId + "_properties.tmp"), null);
333                 }
334             }
335         }
336
337         //req.setAttribute(WebKeys.LANGUAGE_MANAGER_ADDEDKEY,addedKey);
338
req.setAttribute(WebKeys.LANGUAGE_MANAGER_PROPERTIES, properties);
339     }
340
341     private void _save(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form)
342         throws Exception JavaDoc {
343         List JavaDoc list = (List JavaDoc) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST);
344
345         for (int i = 0; i < list.size(); i++) {
346             long langId = ((Language) list.get(i)).getId();
347
348             try {
349                 String JavaDoc filePath = getGlobalVariablesPath() + "cms_language_" +
350                 langId + ".properties";
351                 
352                 String JavaDoc tmpFilePath = getTemporyDirPath() + "cms_language_" +
353                 langId + "_properties.tmp";
354
355                 // Create empty file
356
File JavaDoc from = new java.io.File JavaDoc(tmpFilePath);
357                 from.createNewFile();
358
359                 // Create channel on the source
360
File JavaDoc to = new java.io.File JavaDoc(filePath);
361                 to.createNewFile();
362
363                 FileChannel JavaDoc srcChannel = new FileInputStream JavaDoc(from).getChannel();
364
365                 // Create channel on the destination
366
FileChannel JavaDoc dstChannel = new FileOutputStream JavaDoc(to).getChannel();
367
368                 // Copy file contents from source to destination
369
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
370
371                 // Close the channels
372
srcChannel.close();
373                 dstChannel.close();
374                 
375             } catch (NonWritableChannelException JavaDoc we) {
376                 
377             } catch (IOException JavaDoc e) {
378                 Logger.error(this, "Property File save Failed " + e, e);
379             }
380         }
381         
382         //Calling a thread to update asynchronous the config.xml file
383
//we can't do this in Tomcat, it dies! we can do it in Orion
384
//String webConfigFilePath = config.getPortletContext().getRealPath("/") + "WEB-INF/web.xml";
385
//new ConfigUpdateThread ("ConfigUpdate", webConfigFilePath).start();
386

387         SessionMessages.add(req, "message", "message.languagemanager.save");
388     }
389
390     private void _filterByKey(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form)
391         throws Exception JavaDoc {
392         String JavaDoc strKeySearch = req.getParameter("search");
393
394         if (strKeySearch != null) {
395     
396             Properties JavaDoc[] properties = (Properties JavaDoc[]) req.getAttribute(WebKeys.LANGUAGE_MANAGER_PROPERTIES);
397     
398             ArrayList JavaDoc keyList = new ArrayList JavaDoc();
399     
400             Enumeration JavaDoc e = properties[0].keys();
401     
402             while (e.hasMoreElements()) {
403                 String JavaDoc key = (String JavaDoc) e.nextElement();
404     
405                 if (!key.startsWith(strKeySearch)) {
406                     keyList.add(key);
407                 }
408             }
409     
410             for (int i = 0; i < properties.length; i++) {
411                 Iterator JavaDoc j = keyList.iterator();
412     
413                 while (j.hasNext()) {
414                     String JavaDoc x = (String JavaDoc) j.next();
415     
416                     if (properties[i].containsKey(x)) {
417                         properties[i].remove(x);
418                     }
419                 }
420             }
421     
422             req.setAttribute(WebKeys.LANGUAGE_MANAGER_SEARCH, strKeySearch);
423             req.setAttribute(WebKeys.LANGUAGE_MANAGER_PROPERTIES, properties);
424         }
425         else {
426             req.setAttribute(WebKeys.LANGUAGE_MANAGER_SEARCH, "");
427         }
428     }
429
430     private void _paginateResults(ActionRequest req) throws Exception JavaDoc {
431         int maxRows = 18;
432         int page = 0;
433
434         try {
435             page = Integer.parseInt(req.getParameter("page"));
436
437             if (page < 0) {
438                 page = 0;
439             }
440
441             req.setAttribute("page", String.valueOf(page));
442         } catch (Exception JavaDoc e) {
443         }
444
445         TreeMap JavaDoc[] properties = (TreeMap JavaDoc[]) req.getAttribute(WebKeys.LANGUAGE_MANAGER_PROPERTIES);
446         TreeMap JavaDoc[] newProperties = new TreeMap JavaDoc[properties.length];
447
448         int startRow = maxRows * page;
449         int size = 0;
450         int num = 0;
451
452         for (int i = 0; i < properties.length; i++) {
453             int rowNum = 0;
454             newProperties[i] = new TreeMap JavaDoc();
455
456             Set JavaDoc e = properties[0].keySet();
457             size = properties[0].size();
458             Iterator JavaDoc iter = e.iterator();
459             
460             while (iter.hasNext()) {
461                 String JavaDoc key = (String JavaDoc) iter.next();
462                 String JavaDoc value = (properties[i].get(key) == null) ? "" : (String JavaDoc)properties[i].get(key);
463
464                 if (rowNum >= startRow) {
465                     newProperties[i].put(key, value);
466                 }
467
468                 rowNum++;
469
470                 if (rowNum > (startRow + maxRows)) {
471                     break;
472                 }
473             }
474         }
475
476         if ((size % maxRows) == 0) {
477             num = size / maxRows;
478         } else {
479             num = (size / maxRows) + 1;
480         }
481
482         req.setAttribute(WebKeys.LANGUAGE_MANAGER_PAGE_NUMBERS, String.valueOf(num));
483         req.setAttribute(WebKeys.LANGUAGE_MANAGER_PROPERTIES, newProperties);
484     }
485
486     private void _sortProperties(ActionRequest req) throws Exception JavaDoc {
487         Properties JavaDoc[] properties = (Properties JavaDoc[]) req.getAttribute(WebKeys.LANGUAGE_MANAGER_PROPERTIES);
488         TreeMap JavaDoc[] newProperties = new TreeMap JavaDoc[properties.length];
489
490         for (int i = 0; i < properties.length; i++) {
491             newProperties[i] = new TreeMap JavaDoc(new LanguageManagerComparator());
492             try{
493                 newProperties[i].putAll(properties[i]);
494             }catch(Exception JavaDoc e){
495             }
496         }
497
498         req.setAttribute(WebKeys.LANGUAGE_MANAGER_PROPERTIES, newProperties);
499     }
500     
501     private String JavaDoc getGlobalVariablesPath () {
502         String JavaDoc globalVarsPath = Config.getStringProperty("GLOBAL_VARIABLES_PATH");
503         if (!UtilMethods.isSet(globalVarsPath)) {
504             globalVarsPath = Config.CONTEXT.getRealPath(File.separator + ".." + File.separator + "common" + File.separator + "ext-ejb" + File.separator + "content" + File.separator);
505         }
506         if (!globalVarsPath.endsWith(File.separator))
507             globalVarsPath = globalVarsPath + File.separator;
508         return globalVarsPath;
509     }
510
511     private String JavaDoc getTemporyDirPath () {
512         String JavaDoc tempdir=System.getProperty("java.io.tmpdir");
513         if (tempdir == null)
514             tempdir = "temp";
515         if(!tempdir.endsWith(File.separator))
516             tempdir = tempdir + File.separator;
517         File JavaDoc tempDirFile = new File JavaDoc(tempdir);
518         if (!tempDirFile.exists())
519             tempDirFile.mkdirs();
520         else if (tempDirFile.exists() && tempDirFile.isFile()) {
521             tempDirFile.delete();
522             tempDirFile.mkdirs();
523         }
524         return tempdir;
525     }
526 } //end of the class
527
Popular Tags