View Javadoc

1   /*
2    * This software was designed and created by Jason Carroll.
3    * Copyright (c) 2002, 2003, 2004 Jason Carroll.
4    * The author can be reached at jcarroll@cowsultants.com
5    * ITracker website: http://www.cowsultants.com
6    * ITracker forums: http://www.cowsultants.com/phpBB/index.php
7    *
8    * This program is free software; you can redistribute it and/or modify
9    * it only under the terms of the GNU General Public License as published by
10   * the Free Software Foundation; either version 2 of the License, or
11   * (at your option) any later version.
12   *
13   * This program is distributed in the hope that it will be useful,
14   * but WITHOUT ANY WARRANTY; without even the implied warranty of
15   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   * GNU General Public License for more details.
17   */
18  
19  package org.itracker.web.actions.admin.language;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.lang.reflect.InvocationTargetException;
24  import java.util.Collections;
25  import java.util.Enumeration;
26  import java.util.HashMap;
27  import java.util.Hashtable;
28  import java.util.Locale;
29  import java.util.Map;
30  import java.util.Properties;
31  import java.util.TreeMap;
32  
33  import javax.servlet.ServletException;
34  import javax.servlet.http.HttpServletRequest;
35  import javax.servlet.http.HttpServletResponse;
36  import javax.servlet.http.HttpSession;
37  
38  import org.apache.commons.beanutils.PropertyUtils;
39  import org.apache.log4j.Logger;
40  import org.apache.struts.action.ActionForm;
41  import org.apache.struts.action.ActionForward;
42  import org.apache.struts.action.ActionMapping;
43  import org.apache.struts.action.ActionMessage;
44  import org.apache.struts.action.ActionMessages;
45  import org.itracker.core.resources.ITrackerResources;
46  import org.itracker.model.Language;
47  import org.itracker.model.util.PropertiesFileHandler;
48  import org.itracker.services.ConfigurationService;
49  import org.itracker.services.util.SystemConfigurationUtilities;
50  import org.itracker.services.util.UserUtilities;
51  import org.itracker.web.actions.base.ItrackerBaseAction;
52  import org.itracker.web.forms.LanguageForm;
53  import org.itracker.web.util.Constants;
54  
55  
56  
57  public class EditLanguageFormAction extends ItrackerBaseAction {
58  	private static final Logger log = Logger.getLogger(EditLanguageFormAction.class);
59  
60      public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
61      	ActionMessages errors = new ActionMessages();
62  
63          if(! hasPermission(UserUtilities.PERMISSION_USER_ADMIN, request, response)) {
64              return mapping.findForward("unauthorized");
65          }
66  
67          try {
68              ConfigurationService configurationService = getITrackerServices().getConfigurationService();
69  
70              HttpSession session = request.getSession(true);
71  
72              LanguageForm languageForm = (LanguageForm) form;
73              if(languageForm == null) {
74                  languageForm = new LanguageForm();
75              }
76  
77              String locale = (String) PropertyUtils.getSimpleProperty(form, "locale");
78              int localeType = SystemConfigurationUtilities.getLocaleType(locale);
79              if (localeType == SystemConfigurationUtilities.LOCALE_TYPE_INVALID) {
80              	errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.invalidlocale"));
81              } else {
82                  if("create".equals((String) PropertyUtils.getSimpleProperty(form, "action"))) {
83                      // The locale passed in on a create action is actually the parent locale.  Reset the parent
84                      // locale, increment the type (since we are creating the next type, and clear the locale
85                      localeType++;
86                      languageForm.setParentLocale(locale);
87                      if(localeType == SystemConfigurationUtilities.LOCALE_TYPE_LOCALE) {
88                          languageForm.setLocale(locale + "_");
89                      } else {
90                          languageForm.setLocale("");
91                      }
92                  } 
93  
94                  String[] sortedKeys = configurationService.getSortedKeys();
95                  // Fix for bug in beanutils.  Can remove this logic here and in EditLanguageAction
96                  // once the bug is fixed.
97                  for(int i = 0; i < sortedKeys.length; i++) {
98                      sortedKeys[i] = sortedKeys[i].replace('.', '/');
99                  }
100 
101                 Map<String,String> baseItems = new HashMap<String,String>();
102                 Map<String,String> langItems = new HashMap<String,String>();
103                 Map<String,String> locItems = new HashMap<String,String>();
104                 Map<String,String> items = new HashMap<String,String>();
105                 
106                 log.debug("Loading language elements for edit.  Edit type is " + localeType);
107                 
108                 if (localeType >= SystemConfigurationUtilities.LOCALE_TYPE_BASE) {
109                     baseItems = configurationService.getDefinedKeys(null);
110                     putPropertiesKeys(baseItems, items, ITrackerResources.BASE_LOCALE);
111                     items = baseItems;
112                     log.debug("Base Locale has " + baseItems.size() + " keys defined.");
113                 }
114                 
115                 if (localeType >= SystemConfigurationUtilities.LOCALE_TYPE_LANGUAGE) {
116                     if (!locale.equalsIgnoreCase(ITrackerResources.BASE_LOCALE)) {
117 //                        String parentLocale = ITrackerResources.getParentLocale(locale) ;
118                         String parentLocale = SystemConfigurationUtilities.getLocalePart(locale, SystemConfigurationUtilities.LOCALE_TYPE_LANGUAGE);
119                         languageForm.setParentLocale(parentLocale);
120                         langItems = configurationService.getDefinedKeys(parentLocale);
121                         putPropertiesKeys(langItems, items, parentLocale);
122                         
123                         items = langItems;
124                         log.debug("Language " + parentLocale + " has " + langItems.size() + " keys defined.");
125                     }
126                 }
127                 
128                 if (localeType == SystemConfigurationUtilities.LOCALE_TYPE_LOCALE) {
129                     locItems = configurationService.getDefinedKeys(locale);
130                     putPropertiesKeys(locItems, items, locale);
131                     
132                     items = locItems;
133                     log.debug("Locale " + locale + " has " + locItems.size() + " keys defined.");
134                 }
135                 
136                 if (!"create".equals((String) PropertyUtils.getSimpleProperty(form, "action"))) {
137                     // Fix for bug in beanutils.  Can remove this logic here and in EditLanguageAction
138                     // once the bug is fixed.
139                     // languageForm.set("items", items);
140 //                    for (Iterator<String> iter = baseItems.keySet().iterator(); iter.hasNext(); ) {
141 //                        String key = (String) iter.next();
142 //                        String itemStr = (String) items.get(key);
143 //                        if ( itemStr == null || itemStr.length() == 0 )
144 //                            items.put(key,"");
145 //                    }
146 
147                     Map<String,String> formItems = new HashMap<String,String>();
148                     for (Enumeration<String> en = ITrackerResources.getBundle(locale).getKeys(); en.hasMoreElements(); ) {
149                         String key = en.nextElement();
150                         formItems.put(key, "");
151                     }
152                     formItems.putAll(items);
153                     
154                     languageForm.setItems(new TreeMap<String, String>(formItems));
155                 } else {
156                     String parentLocale = null;
157                     
158                     if (!locale.equalsIgnoreCase(ITrackerResources.BASE_LOCALE)) {
159                         parentLocale = SystemConfigurationUtilities.getLocalePart(locale, SystemConfigurationUtilities.LOCALE_TYPE_LANGUAGE);
160                     }
161                     langItems = configurationService.getDefinedKeys(parentLocale);
162                     
163                     Map<String,String> formItems = new HashMap<String,String>();
164             		if (log.isDebugEnabled()) {
165             			log.debug("putPropertiesKeys: items: " + items);
166             		}
167                     for (Enumeration<String> en = ITrackerResources.getBundle(locale).getKeys(); en.hasMoreElements(); ) {
168                         String key = en.nextElement();
169                         formItems.put(key, "");
170                     }
171                     
172                     formItems.putAll(items);
173                     
174                     languageForm.setItems(new TreeMap<String, String>(formItems));
175                     
176                 }
177                 Language languageItem = null;
178                 Locale curLocale = ITrackerResources.getLocale(locale);
179 //                try {
180 //                	languageItem = configurationService.getLanguageItemByKey("itracker.locale.name", curLocale);
181 //                } catch (RuntimeException e) {
182             	languageItem = new Language(locale, "itracker.locale.name",
183             			ITrackerResources.getString("itracker.locale.name", curLocale));// configurationService.getLanguageItemByKey("itracker.locale.name", curLocale);
184 //                }
185                 languageForm.setLocaleTitle(languageItem.getResourceValue());
186                 languageItem = new Language(locale, "itracker.locale.name",
187             			ITrackerResources.getString("itracker.locale.name." + locale, ITrackerResources.BASE_LOCALE));// configurationService.getLanguageItemByKey("itracker.locale.name", curLocale);
188 //                }
189                 languageForm.setLocaleBaseTitle(languageItem.getResourceValue());
190                 session.setAttribute(Constants.EDIT_LANGUAGE_KEYS_KEY, sortedKeys);
191                 session.setAttribute(Constants.EDIT_LANGUAGE_BASE_KEY, baseItems);
192                 session.setAttribute(Constants.EDIT_LANGUAGE_LANG_KEY, langItems);
193                 session.setAttribute(Constants.EDIT_LANGUAGE_LOC_KEY, locItems);
194                 session.setAttribute(Constants.EDIT_LANGUAGE_TYPE_KEY, localeType);
195                 request.setAttribute("languageForm", languageForm);
196                 if (log.isDebugEnabled()) {
197                 	log.debug("Locale = " + languageForm.getLocale());
198                 }
199                 saveToken(request);
200                 return mapping.getInputForward();
201             }
202         } catch(RuntimeException e) {
203             log.error("Exception while creating edit language form.", e);
204             errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
205         } catch (IllegalAccessException e) {
206             log.error("Exception while creating edit language form.", e);
207             errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
208 		} catch (InvocationTargetException e) {
209             log.error("Exception while creating edit language form.", e);
210             errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
211 		} catch (NoSuchMethodException e) {
212             log.error("Exception while creating edit language form.", e);
213             errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
214 		}
215 
216         if(! errors.isEmpty()) {
217             saveErrors(request, errors);
218         }
219 
220         return mapping.findForward("error");
221     }
222     @SuppressWarnings("unchecked")
223 	void putPropertiesKeys(Map<String, String> locItems, Map<String, String> items, String locale) {
224         try {      	
225         	Hashtable<Object, Object> p;
226         	try {
227         		String path = File.separatorChar + ITrackerResources.RESOURCE_BUNDLE_NAME.replace('.', File.separatorChar) + (null != locale && !(ITrackerResources.BASE_LOCALE.equals(locale))? "_" + locale: "") + ".properties";
228         		if (log.isDebugEnabled()) {
229         			log.debug("putPropertiesKeys: loading: " + path);
230         		}
231         		p = new PropertiesFileHandler(path).getProperties();
232         		p = new Hashtable<Object, Object>(p);
233         		
234         		if (log.isDebugEnabled()) {
235         			log.debug("putPropertiesKeys: loaded properties: " + p);
236         		}
237         	} catch (Exception e) {
238         		if (log.isDebugEnabled()) {
239         			log.debug("putPropertiesKeys", e);
240         		}
241         		p = new Properties();
242         	}
243         	// overload properties by loc items from db
244 			if (log.isDebugEnabled()) {
245 				log.debug("putPropertiesKeys: overloading locItems: " + locItems);
246 			}
247 //        	Map<Object, Object> pMap = new HashMap<Object, Object>(p);
248         	p.putAll(locItems);
249         	locItems.putAll(Collections.checkedMap((Map)p, String.class, String.class));
250         	
251         } catch (RuntimeException e) {
252         	log.error("addPropertiesKeys: caught ", e);
253         }
254     }
255 }
256