View Javadoc

1   /**
2    * 2007, Digitalis Informatica. All rights reserved. Distribuicao e Gestao de Informatica, Lda. Estrada de Paco de Arcos
3    * num.9 - Piso -1 2780-666 Paco de Arcos Telefone: (351) 21 4408990 Fax: (351) 21 4408999 http://www.digitalis.pt
4    */
5   
6   package pt.digitalis.dif.codegen.templates;
7   
8   import java.util.List;
9   
10  import pt.digitalis.dif.controller.ExceptionHandlers;
11  import pt.digitalis.dif.controller.http.HTTPConstants;
12  import pt.digitalis.dif.controller.interfaces.IDIFContext;
13  import pt.digitalis.dif.controller.interfaces.IDispatcherErrorHandler;
14  import pt.digitalis.dif.dem.CallbackType;
15  import pt.digitalis.dif.dem.interfaces.IProvider;
16  import pt.digitalis.dif.dem.interfaces.IStageInstance;
17  import pt.digitalis.dif.dem.managers.IDEMManager;
18  import pt.digitalis.dif.dem.managers.IMessageManager;
19  import pt.digitalis.dif.dem.managers.IParameterManager;
20  import pt.digitalis.dif.dem.managers.IRegistrationManager;
21  import pt.digitalis.dif.dem.objects.EventType;
22  import pt.digitalis.dif.dem.objects.ViewObject;
23  import pt.digitalis.dif.dem.objects.parameters.IParameters;
24  import pt.digitalis.dif.dem.objects.parameters.ParameterScope;
25  import pt.digitalis.dif.exception.InternalFrameworkException;
26  import pt.digitalis.dif.ioc.DIFIoCRegistry;
27  import pt.digitalis.dif.utils.extensions.document.IDocumentRepositoryManager;
28  import pt.digitalis.dif.utils.logging.DIFLogger;
29  import pt.digitalis.utils.common.StringUtils;
30  
31  /**
32   * Resources used by the DEM Entity templates on the code generation.
33   * 
34   * @author Pedro Viegas <a href="mailto:pviegas@digitalis.pt">pviegas@digitalis.pt</a>
35   * @author Rodrigo Gonçalves <a href="mailto:rgoncalves@digitalis.pt">rgoncalves@digitalis.pt</a>
36   * @created Nov 6, 2007
37   */
38  public final class TemplateResources {
39  
40      /*
41       * Implementation Note: This class holds resources used by the DEM entity templates. Since copying from template
42       * doesn't initialize properly the private attributes, the resources used by the enhanced entities were placed on
43       * this class thus enabling the entities to access them as needed.
44       */
45  
46      /** The DEM manager. */
47      static private IDEMManager demManager = DIFIoCRegistry.getRegistry().getImplementation(IDEMManager.class);
48  
49      /** The document repository manager. */
50      static private IDocumentRepositoryManager documentRepositoryManager = null;
51  
52      /** Singleton instance */
53      static private TemplateResources instance = null;
54  
55      /** The message manager. */
56      static private IMessageManager messageManager = DIFIoCRegistry.getRegistry().getImplementation(
57              IMessageManager.class);
58  
59      /** The parameter manager */
60      static private IParameterManager parameterManager = DIFIoCRegistry.getRegistry().getImplementation(
61              IParameterManager.class);
62  
63      /** The registration manager. */
64      static private IRegistrationManager registrationManager = DIFIoCRegistry.getRegistry().getImplementation(
65              IRegistrationManager.class);
66  
67      /**
68       * Returns a callback type
69       * 
70       * @param id
71       *            the id of the call back to return
72       * @return the registrationManager
73       */
74      static public CallbackType getCallBack(String id)
75      {
76          return CallbackType.valueOf(id);
77      }
78  
79      /**
80       * Returns the DEM manager.
81       * 
82       * @return the demManager
83       */
84      static public IDEMManager getDEMManager()
85      {
86          return TemplateResources.demManager;
87      }
88  
89      /**
90       * Inspector for the 'documentRepositoryManager' attribute.
91       * 
92       * @return the documentRepositoryManager value
93       */
94      public static IDocumentRepositoryManager getDocumentRepositoryManager()
95      {
96          if (documentRepositoryManager == null)
97              documentRepositoryManager = DIFIoCRegistry.getRegistry()
98                      .getImplementation(IDocumentRepositoryManager.class);
99  
100         return documentRepositoryManager;
101     }
102 
103     /**
104      * Returns an event type
105      * 
106      * @param id
107      *            the id of the event to return
108      * @return the registrationManager
109      */
110     static public EventType getEventType(String id)
111     {
112         return EventType.valueOf(id);
113     }
114 
115     /**
116      * @return the singleton instance
117      */
118     static public TemplateResources getInstance()
119     {
120         if (instance == null)
121             instance = new TemplateResources();
122 
123         return instance;
124     }
125 
126     /**
127      * Returns an IoC implementation
128      * 
129      * @param clazz
130      *            the class that defines the implementation interface
131      * @return the implementation
132      */
133     static public Object getIoCImplementation(String clazz)
134     {
135         try
136         {
137             return DIFIoCRegistry.getRegistry().getImplementation(Class.forName(clazz));
138         }
139         catch (ClassNotFoundException e)
140         {
141             return null;
142         }
143     }
144 
145     /**
146      * Returns the message manager.
147      * 
148      * @return the messageManager
149      */
150     static public IMessageManager getMessageManager()
151     {
152         return TemplateResources.messageManager;
153     }
154 
155     /**
156      * Returns the parameter manager.
157      * 
158      * @return the parameterManager
159      */
160     static public IParameterManager getParameterManager()
161     {
162         return TemplateResources.parameterManager;
163     }
164 
165     /**
166      * Returns the parameter scope
167      * 
168      * @param scope
169      *            the scope as a param
170      * @return the parameter scope
171      */
172     static public ParameterScope getParameterScope(String scope)
173     {
174         return ParameterScope.valueOf(scope);
175     }
176 
177     /**
178      * Returns a IParameters instance Development note: This is a workaround for a Javassist bug. Could not have this
179      * line of the generated code.
180      * 
181      * @param stage
182      *            the stage to get the parameters for
183      * @return the registrationManager
184      */
185     static public IParameters getParametersInstance(IStageInstance stage)
186     {
187         IParameters parameters = DIFIoCRegistry.getRegistry().getImplementation(IParameters.class);
188         parameters.initialize(stage);
189 
190         return parameters;
191     }
192 
193     /**
194      * Returns the providers as a List of {@link IProvider}
195      * 
196      * @return the registrationManager
197      */
198     static public List<IProvider> getProvidersAsList()
199     {
200         return java.util.Arrays.asList(getDEMManager().getProviders().values().toArray(new IProvider[] {null}));
201     }
202 
203     /**
204      * Returns the registration manager.
205      * 
206      * @return the registrationManager
207      */
208     static public IRegistrationManager getRegistrationManager()
209     {
210         return TemplateResources.registrationManager;
211     }
212 
213     /**
214      * returns a given parameter form the request
215      * 
216      * @param context
217      *            the current context
218      * @param id
219      *            the Id of the desired parameter
220      * @return the parameter value as string
221      */
222     static public String getRequestParameter(IDIFContext context, String id)
223     {
224         if (context != null && context.getRequest() != null)
225         {
226             Object result = context.getRequest().getParameter(id.toLowerCase());
227 
228             if (result == null)
229                 return null;
230             else
231                 return result.toString();
232 
233         }
234         else
235             return null;
236     }
237 
238     /** Private constructor. Singleton implementation */
239     private TemplateResources()
240     {}
241 
242     /**
243      * The stage execute logic
244      * 
245      * @param stageInstance
246      * @param context
247      * @return the view object to render the stage output in
248      */
249     public ViewObject stageExecute(IStageInstance stageInstance, IDIFContext context)
250     {
251         // Declare result variable
252         ViewObject result = null;
253 
254         // Will determine if we should return the default view. According to the event of default execution handler.
255         boolean returnDefaultView = true;
256 
257         try
258         {
259             // FIXME: Refactor so that the AbstractDIFDispatcher remains abstracted from the HTTP
260             // implementation. Use generic EventHandlers, instead of formSubmit
261             Object submitStage = context.getRequest().getParameter(HTTPConstants.FORM_SUBMIT_STAGE);
262             Object submitForm = context.getRequest().getParameter(HTTPConstants.FORM_SUBMIT_NAME);
263             Object submitFormValidationRequest = context.getRequest().getParameter(HTTPConstants.FORM_VALIDATION);
264             boolean isFormValidationRequest = Boolean.parseBoolean(StringUtils.nvl(
265                     StringUtils.toStringOrNull(submitFormValidationRequest), "false"));
266 
267             Object eventID = context.getRequest().getParameter(HTTPConstants.EVENT_ID);
268 
269             // If form submitted check if an event handler of validation type for it exists (must call it prior to the
270             // submit itself)
271             if (stageInstance.getID().equalsIgnoreCase((String) submitStage)
272                     && stageInstance.hasValidationLogicForForm(StringUtils.toStringOrNull(submitForm)))
273                 stageInstance.callExecuteOnEventMethod(context, EventType.FORM_VALIDATION, submitForm.toString());
274 
275             // If form submitted check if an event handler for it exists
276             if (isFormValidationRequest && stageInstance.getID().equalsIgnoreCase((String) submitStage)
277                     && stageInstance.hasValidationLogicForForm(StringUtils.toStringOrNull(submitForm)))
278             {
279                 // The validation function has already been called. No other action is needed
280                 // Result can only be null here so no action is required
281             }
282             // If form submitted check if an event handler for it exists
283             else if (stageInstance.getID().equalsIgnoreCase((String) submitStage)
284                     && (stageInstance.getEventHandlers().get(EventType.FORM_SUBMIT).contains(submitForm)
285                             || stageInstance.getEventHandlers().get(EventType.FORM_SUBMIT_SAVE_ACTION)
286                                     .contains(submitForm) || stageInstance.getEventHandlers()
287                             .get(EventType.FORM_SUBMIT_AJAX_REQUEST).contains(submitForm)))
288             {
289                 // Execute specific on submit event handler
290                 if (context.getRequest().isAjaxMode())
291                 {
292                     result = stageInstance.callExecuteOnEventMethod(context, EventType.FORM_SUBMIT_AJAX_REQUEST,
293                             submitForm.toString());
294                     returnDefaultView = true;
295                 }
296                 else
297                 {
298                     result = stageInstance.callExecuteOnEventMethod(context, EventType.FORM_SUBMIT,
299                             submitForm.toString());
300                 }
301             }
302             else
303             {
304                 boolean resultProcessed = false;
305 
306                 if (eventID != null)
307                 {
308                     for (EventType type: stageInstance.getEventHandlers().keySet())
309                     {
310                         for (String currentEventID: stageInstance.getEventHandlers().get(type))
311                         {
312                             if (currentEventID.equalsIgnoreCase(eventID.toString()))
313                             {
314                                 // Execute specific on submit event handler
315                                 DIFLogger.getLogger().debug("_CG_execute: " + stageInstance.getID());
316                                 DIFLogger.getLogger().debug("Event: " + eventID + "(" + type + ")");
317 
318                                 result = stageInstance.callExecuteOnEventMethod(context, type, currentEventID);
319                                 resultProcessed = true;
320 
321                                 returnDefaultView = returnDefaultView && (type != EventType.AJAX_REQUEST)
322                                         && (type != EventType.DOCUMENT_TYPE);
323 
324                                 break;
325                             }
326                         }
327 
328                         if (resultProcessed)
329                             break;
330                     }
331                 }
332 
333                 if (!resultProcessed)
334                     // Execute normal business logic
335                     result = stageInstance.callExecuteMethod(context);
336             }
337 
338             // If execution was OK but no view was returned set the result as the default view
339             if (result == null && returnDefaultView)
340                 result = stageInstance.getDefaultView();
341 
342         }
343         catch (Exception exception)
344         {
345             exception.printStackTrace();
346             String exceptionType = exception.getClass().getCanonicalName();
347 
348             // If an exception was raised check if there's a redirection to trigger...
349             // ...current stage error view...
350             if (stageInstance.getInjectedErrorViews().size() != 0
351                     && stageInstance.getInjectedErrorViews().containsKey(exceptionType))
352             {
353                 context.addStageResult(IDispatcherErrorHandler.EXCEPTION, exception);
354                 result = stageInstance.getInjectedErrorViews().get(exceptionType);
355 
356             }
357             // ...current stage error stage...
358             else if (stageInstance.getInjectedErrorStages().size() != 0
359                     && stageInstance.getInjectedErrorStages().containsKey(exceptionType))
360             {
361                 context.addStageResult(IDispatcherErrorHandler.EXCEPTION, exception);
362                 context.redirectTo(stageInstance.getInjectedErrorStages().get(exceptionType));
363 
364             }
365             // ...system wide exception handler stage...
366             else if (ExceptionHandlers.hasHandler(exception))
367             {
368                 ExceptionHandlers.handleException(context, exception);
369             }
370             else
371                 throw new RuntimeException(
372                         "Unable to proceed! A business exception was raised and no error views or stages were"
373                                 + " defined for redirection. Aborting... ", new InternalFrameworkException(exception,
374                                 context));
375         }
376 
377         return result;
378     }
379 }