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.configuration;
20  
21  import java.io.IOException;
22  import java.util.HashSet;
23  import java.util.List;
24  
25  import javax.naming.InitialContext;
26  import javax.servlet.ServletException;
27  import javax.servlet.http.HttpServletRequest;
28  import javax.servlet.http.HttpServletResponse;
29  import javax.servlet.http.HttpSession;
30  
31  import org.apache.log4j.Logger;
32  import org.apache.struts.action.ActionForm;
33  import org.apache.struts.action.ActionForward;
34  import org.apache.struts.action.ActionMapping;
35  import org.apache.struts.action.ActionMessage;
36  import org.apache.struts.action.ActionMessages;
37  import org.itracker.core.resources.ITrackerResources;
38  import org.itracker.model.AbstractEntity;
39  import org.itracker.model.Component;
40  import org.itracker.model.Configuration;
41  import org.itracker.model.CustomField;
42  import org.itracker.model.ImportDataModel;
43  import org.itracker.model.Issue;
44  import org.itracker.model.IssueAttachment;
45  import org.itracker.model.IssueField;
46  import org.itracker.model.IssueHistory;
47  import org.itracker.model.Language;
48  import org.itracker.model.Project;
49  import org.itracker.model.User;
50  import org.itracker.model.Version;
51  import org.itracker.services.ConfigurationService;
52  import org.itracker.services.IssueService;
53  import org.itracker.services.ProjectService;
54  import org.itracker.services.UserService;
55  import org.itracker.services.exceptions.PasswordException;
56  import org.itracker.services.exceptions.UserException;
57  import org.itracker.services.util.CustomFieldUtilities;
58  import org.itracker.services.util.ImportExportUtilities;
59  import org.itracker.services.util.SystemConfigurationUtilities;
60  import org.itracker.services.util.UserUtilities;
61  import org.itracker.web.actions.base.ItrackerBaseAction;
62  import org.itracker.web.util.Constants;
63  
64  
65  
66  public class ImportDataProcessAction extends ItrackerBaseAction {
67  	private static final Logger log = Logger.getLogger(ImportDataProcessAction.class);
68  
69      public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
70          ActionMessages errors = new ActionMessages();
71  
72  
73          if(! hasPermission(UserUtilities.PERMISSION_USER_ADMIN, request, response)) {
74              return mapping.findForward("unauthorized");
75          }
76  
77          try {
78              InitialContext ic = new InitialContext();
79  
80              HttpSession session = request.getSession(true);
81              User importer = (User) session.getAttribute(Constants.USER_KEY);
82              if(importer == null) {
83                  return mapping.findForward("unauthorized");
84              }
85  
86              ImportDataModel model = (ImportDataModel) session.getAttribute(Constants.IMPORT_DATA_KEY);
87              if (log.isDebugEnabled())
88              	log.debug("Importing configuration data.");
89              createConfig(model, importer, ic);
90              if (log.isDebugEnabled())
91              	log.debug("Importing user data.");
92              createUsers(model, importer, ic);
93              if (log.isDebugEnabled())
94              	log.debug("Importing project data.");
95              createProjects(model, importer, ic);
96              if (log.isDebugEnabled())
97              	log.debug("Importing issue data.");
98              createIssues(model, importer, ic);
99              if (log.isDebugEnabled())
100             	log.debug("Import complete.");
101 
102         } catch(Exception e) {
103             log.error("Exception while importing data.", e);
104             errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
105         }
106 
107         if(! errors.isEmpty()) {
108             saveErrors(request, errors);
109             return mapping.findForward("error");
110         } else {
111         	errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.importexport.importcomplete"));
112             saveMessages(request, errors);
113         }
114 
115         return mapping.findForward("adminindex");
116     }
117 
118     private boolean createConfig(ImportDataModel model, User importer, InitialContext ic) {
119         try {
120             ConfigurationService configurationService = getITrackerServices().getConfigurationService();
121 
122             AbstractEntity[] importData = model.getData();
123             for(int i = 0; i < importData.length; i++) {
124                 if(importData[i] instanceof Configuration && ! model.getExistingModel(i)) {
125                     Configuration configItem = (Configuration) importData[i];
126                     Configuration newConfigItem = configurationService.createConfigurationItem(configItem);
127                     configItem.setId(newConfigItem.getId());
128 
129                     // Now add a new language key
130                     String key = SystemConfigurationUtilities.getLanguageKey(configItem);
131                     configurationService.updateLanguageItem(new Language(ImportExportUtilities.EXPORT_LOCALE_STRING, key, configItem.getName()));
132                     ITrackerResources.clearKeyFromBundles(key, true);
133                 } else if(importData[i] instanceof CustomField && ! model.getExistingModel(i)) {
134                     CustomField customField = (CustomField) importData[i];
135                     CustomField newCustomField = configurationService.createCustomField(customField);
136                     customField.setId(newCustomField.getId());
137 
138                     // Now add new language keys.  One for the field and then add one for for
139                     // each option that exists.
140                     String key = CustomFieldUtilities.getCustomFieldLabelKey(customField.getId());
141                 	// TODO, removed name attribute, so it's defaulted to the key
142                     configurationService.updateLanguageItem(new Language(ImportExportUtilities.EXPORT_LOCALE_STRING, key, key));
143                     ITrackerResources.clearKeyFromBundles(key, true);
144                     if(customField.getFieldType() == CustomField.Type.LIST) {
145                     	// TODO, removed name attribute, so it's defaulted to the key
146                         for(int j = 0; j < customField.getOptions().size(); j++) {
147                             String optionKey = CustomFieldUtilities.getCustomFieldOptionLabelKey(customField.getId(), customField.getOptions().get(j).getId());
148                             configurationService.updateLanguageItem(new Language(ImportExportUtilities.EXPORT_LOCALE_STRING, optionKey, optionKey));
149                             ITrackerResources.clearKeyFromBundles(optionKey, true);
150                         }
151                     }
152                 }
153             }
154             configurationService.resetConfigurationCache();
155         } catch(RuntimeException e) {
156             return false;
157         }
158 
159         return true;
160     }
161 
162     private boolean createUsers(ImportDataModel model, User importer, InitialContext ic) {
163         try {
164             UserService userService = getITrackerServices().getUserService();
165 
166             AbstractEntity[] importData = model.getData();
167             for(int i = 0; i < importData.length; i++) {
168                 if(importData[i] instanceof User && ! model.getExistingModel(i)) {
169                     User user = (User) importData[i];
170                     user.setRegistrationType(UserUtilities.REGISTRATION_TYPE_IMPORT);
171                     if(model.getCreatePasswords()) {
172                         user.setPassword(UserUtilities.encryptPassword(user.getLogin()));
173                     }
174                     user.setLogin(user.getLogin());
175                     User newUser = userService.createUser(user);
176                     user.setId(newUser.getId());
177                 }
178             }
179         } catch(RuntimeException e) {
180             return false;
181         } catch (PasswordException e) {
182 			return false;
183 		} catch (UserException e) {
184 			return false;
185 		}
186 
187         return true;
188     }
189 
190     private boolean createProjects(ImportDataModel model, User importer, InitialContext ic) {
191         try {
192             ProjectService projectService = getITrackerServices().getProjectService();
193 
194             AbstractEntity[] importData = model.getData();
195             for(int i = 0; i < importData.length; i++) {
196                 if(importData[i] instanceof Project && ! model.getExistingModel(i)) {
197                     Project project = (Project) importData[i];
198                     project = projectService.createProject(project, importer.getId());
199 //                    projectService.getProjectDAO().save(project);
200 
201                     HashSet<Integer> setOfOwnerIDs = new HashSet<Integer>();
202                     for(int j = 0; j < project.getOwners().size(); j++) {
203                     	setOfOwnerIDs.add(project.getOwners().get(j).getId());
204                     }
205                     projectService.setProjectOwners(project, setOfOwnerIDs);
206 
207                     HashSet<Integer> setOfFieldIds = new HashSet<Integer>();
208                     for(int j = 0; j < project.getCustomFields().size(); j++) {
209                     	setOfFieldIds.add(project.getCustomFields().get(j).getId());
210                     }
211                     projectService.setProjectFields(project, setOfFieldIds);
212 
213                     List<Component> components = project.getComponents();
214                     for(int j = 0; j < components.size(); j++) {
215                         Component newComponent = projectService.addProjectComponent(project.getId(), components.get(j));
216                         components.get(j).setId(newComponent.getId());
217                     }
218 
219                     List<Version> versions = project.getVersions();
220                     for(int j = 0; j < versions.size(); j++) {
221                         Version newVersion = projectService.addProjectVersion(project.getId(), versions.get(j));
222                         versions.get(j).setId(newVersion.getId());
223                     }
224                 }
225             }
226         } catch(RuntimeException e) {
227             return false;
228         }
229 
230         return true;
231     }
232 
233     private boolean createIssues(ImportDataModel model, User importer, InitialContext ic) {
234         try {
235             IssueService issueService = getITrackerServices().getIssueService();
236 
237             AbstractEntity[] importData = model.getData();
238             for(int i = 0; i < importData.length; i++) {
239                 if(importData[i] instanceof Issue && ! model.getExistingModel(i)) {
240                     Issue issue = (Issue) importData[i];
241                     Issue newIssue = issueService.createIssue(issue, 
242                             issue.getProject().getId(), issue.getCreator().getId(), importer.getId());
243                     issue.setId(newIssue.getId());
244 
245                     // Assign the issue
246                     if(issue.getOwner() != null) {
247                         issueService.assignIssue(issue.getId(), issue.getOwner().getId(), importer.getId());
248                     }
249 
250                     // Now set Issue Custom Fields
251                     List<IssueField> fields = issue.getFields();
252                     if(fields.size() > 0) {
253                         for(int j = 0; j < fields.size(); j++) {
254                             fields.get(j).setIssue(issue);
255                         }
256                         issueService.setIssueFields(issue.getId(), issue.getFields());
257                     }
258 
259                     // Now add all the issue history
260                     List<IssueHistory> history = issue.getHistory();
261                     if(history.size() > 0) {
262                         for(int j = 0; j < history.size(); j++) {
263                             history.get(j).setIssue(issue);
264                             
265                             issueService.updateIssue(issue, importer.getId());
266                         }
267                     }
268 
269                     // Now add components and versions
270                     HashSet<Integer> components = new HashSet<Integer>();
271                     List<Component> componentsList = issue.getComponents();
272                     if(componentsList.size() > 0) {
273                         for(int j = 0; j < componentsList.size(); j++) {
274                             components.add(componentsList.get(j).getId());
275                         }
276                         issueService.setIssueComponents(issue.getId(), components, importer.getId());
277                     }
278                     HashSet<Integer> versions = new HashSet<Integer>();
279                     List<Version> versionsList = issue.getVersions();
280                     if(versionsList.size() > 0) {
281                         for(int j = 0; j < versionsList.size(); j++) {
282                             versions.add(versionsList.get(j).getId());
283                         }
284                         issueService.setIssueVersions(issue.getId(), versions, importer.getId());
285                     }
286 
287                     // Now add any attachments
288                     List<IssueAttachment> attachments = issue.getAttachments();
289                     if(attachments.size() > 0) {
290                         for(int j = 0; j < history.size(); j++) {
291                             attachments.get(j).setIssue(issue);
292                             issueService.addIssueAttachment(attachments.get(j), null);
293                         }
294                     }
295                 }
296             }
297         } catch(Exception e) {
298             return false;
299         }
300 
301         return true;
302     }
303 
304     // TODO: it looks like the following method is not used; commented and task added
305    // private void printArray(AbstractBean[] models) {
306     //    for(int i = 0; i < models.length; i++) {
307      //       logger.debug(i + ") " + models[i].toString());
308       //  }
309    // }
310 
311 }
312