View Javadoc

1   /* ==============================================================================
2    *   JDBCAdmin, data management software.
3    *   Copyright (C) 2005  Norsys S.A
4    *
5    *   This library is free software; you can redistribute it and/or
6    *   modify it under the terms of the GNU Lesser General Public
7    *   License as published by the Free Software Foundation; either
8    *   version 2.1 of the License, or (at your option) any later version.
9    *
10   *   This library is distributed in the hope that it will be useful,
11   *   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   *   Lesser General Public License for more details.
14   *
15   *   You should have received a copy of the GNU Lesser General Public
16   *   License along with this library; if not, write to the Free Software
17   *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18   * ==============================================================================
19   */
20  package jdbcadmin.web.actions;
21  
22  import java.io.File;
23  import java.net.MalformedURLException;
24  import java.net.URL;
25  
26  import javax.naming.Context;
27  import javax.naming.InitialContext;
28  import javax.naming.NameNotFoundException;
29  import javax.servlet.http.HttpServletRequest;
30  import javax.servlet.http.HttpServletResponse;
31  
32  import jdbcadmin.core.data.ConnectionInfo;
33  import jdbcadmin.core.exceptions.TechnicalException;
34  import jdbcadmin.core.tools.ConfigurationHandler;
35  import jdbcadmin.web.ContexteManager;
36  import jdbcadmin.web.forms.ConnectionForm;
37  
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  import org.apache.struts.action.Action;
41  import org.apache.struts.action.ActionError;
42  import org.apache.struts.action.ActionErrors;
43  import org.apache.struts.action.ActionForm;
44  import org.apache.struts.action.ActionForward;
45  import org.apache.struts.action.ActionMapping;
46  
47  /***
48   * @author Thomas Recloux (trecloux@norsys.fr)
49   * @struts.action
50   * path="/index"
51   * @struts.action-forward
52   * name="cnxPage"
53   * path="/connection.jsp"
54   * @struts.action-forward
55   * name="main"
56   * path="/listSchema.do"
57   */
58  public class IndexAction extends Action {
59  
60      /*** param mode. */
61      private static final String MODE_PARAM = "param";
62      /*** User mode. */
63      private static final String MODE_USER  = "user";
64  
65      /*** Logger */
66      private static Log logger = LogFactory.getLog(IndexAction.class);
67  
68      /***
69       * Index action, tests parameters, connect to the db and forward to the connection page
70       * {@inheritDoc}
71       */
72      public ActionForward execute(
73              ActionMapping aMapping, ActionForm aForm,
74              HttpServletRequest aRequest, HttpServletResponse aResponse) throws Exception {
75  
76          String forward = "main";
77          ActionErrors errors = new ActionErrors();
78          try {
79              // traitement
80              ConfigurationHandler config = ConfigurationHandler.loadConfig(findConfig().openStream());
81              ConnectionInfo cnxInfo = config.getConnexionInfo();
82              ContexteManager.setRestrictions(aRequest, config.getAccessAuthorizations());
83              ContexteManager.setLabel(aRequest, config.getLabel());
84              String mode = cnxInfo.getMode();
85              if (MODE_PARAM.equals(mode)) {
86                  // The configuration is set up in a file
87                  ContexteManager.setCnxInfos(aRequest, cnxInfo);
88              } else if (MODE_USER.equals(mode)) {
89                  // The configuration is filled by the user
90                  forward = "cnxPage";
91                  // On initialise les champs avec les valeurs paramètrées
92                  ConnectionForm form = new ConnectionForm();
93                  form.setUrl(cnxInfo.getUrl());
94                  form.setDriverName(cnxInfo.getDriverName());
95                  form.setUserName(cnxInfo.getUserName());
96                  form.setUserPassword(cnxInfo.getUserPassword());
97                  form.setJndiName(cnxInfo.getDataSourceJndiName());
98                  aRequest.setAttribute("connectionForm", form);
99              } else {
100                 errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("erreur.badconfig"));
101                 forward = "error";
102             }
103 
104         } catch (Exception e) { // managing errors
105             if (logger.isErrorEnabled()) {
106                 logger.error("Unexpected error during the index action", e);
107             }
108             errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.generic", e.getMessage()));
109             forward = "error";
110         }
111         if (!errors.isEmpty()) {
112             saveErrors(aRequest, errors);
113         }
114         return aMapping.findForward(forward); // recherche et retour du mapping pour le forward logique
115     }
116 
117     /***
118      * Find the config file
119      * @return the URL of the config file
120      * @throws TechnicalException erreur technique
121      */
122     private URL findConfig() throws TechnicalException {
123         try {
124             // url du fichier de conf
125             URL url = searchConfigUrlInSysProperties();
126             if (url == null) {
127                 url = searchConfigUrlJndiResources();
128                 if (url == null) {
129                     url = getServlet().getServletContext().getResource(Constants.EMBEDDED_CONFIG_FILE);
130                 }
131             }
132             return url;
133         } catch (MalformedURLException mue) {
134             throw new TechnicalException("Error getting the configuration file", mue);
135         }
136     }
137 
138     /***
139      * Search the congig file from the system properties
140      * @return the URL of the conf file
141      */
142     private URL searchConfigUrlInSysProperties() {
143         try {
144             if (System.getProperty(Constants.CONFIG_FILE_SYSPROPERTY) != null) {
145                 File fic = new File(System.getProperty(Constants.CONFIG_FILE_SYSPROPERTY));
146                 if (fic.exists()) {
147                     return fic.toURL();
148                 } else {
149                     if (logger.isWarnEnabled()) {
150                         logger.warn("The config file specified in the system properties "
151                                 + "could not be found : |" + fic + "|");
152                     }
153                     return null;
154                 }
155             } else {
156                 return null;
157             }
158         } catch (Exception e) {
159             if (logger.isWarnEnabled()) {
160                 logger.warn("Error searching the config file from system properties", e);
161             }
162             return null;
163         }
164     }
165 
166     /***
167      * Search the config file in the JNDI tree.
168      * @return the url of the conf file
169      */
170     private URL searchConfigUrlJndiResources() {
171         try {
172             Context ctx = new InitialContext();
173             String prop = (String) ctx.lookup(Constants.CONFIG_FILE_JNDI_KEY);
174             File fic = new File(prop);
175             if (fic.exists()) {
176                 return fic.toURL();
177             } else {
178                 if (logger.isWarnEnabled()) {
179                     logger.warn("The configuration file specified in the global JNDI tree could not be found: |"
180                             + fic + "|");
181                 }
182                 return null;
183             }
184         } catch (NameNotFoundException nne) {
185             if (logger.isWarnEnabled()) {
186                 logger.warn("Error JNDI name not found in global JNDI tree");
187             }
188             try {
189                 Context ctx = new InitialContext();
190                 ctx = (Context) ctx.lookup("java:comp/env");
191                 String prop = (String) ctx.lookup(Constants.CONFIG_FILE_JNDI_KEY);
192                 File fic = new File(prop);
193                 if (fic.exists()) {
194                     return fic.toURL();
195                 } else {
196                     if (logger.isWarnEnabled()) {
197                         logger.warn("The configuration file specified in the application JNDI tree "
198                                 + "could not be found: |" + fic + "|");
199                     }
200                     return null;
201                 }
202             } catch (NameNotFoundException nne2) {
203                 if (logger.isWarnEnabled()) {
204                     logger.warn("Error JNDI name not found in application JNDI tree");
205                 }
206             } catch (Exception e) {
207                 if (logger.isWarnEnabled()) {
208                     logger.warn("Error searching the configuration file URL's JNDI in application JNDI tree");
209                 }
210                 return null;
211             }
212             return null;
213         } catch (Exception e) {
214             if (logger.isWarnEnabled()) {
215                 logger.warn("Error searching the configuration file URL's JNDI in global JNDI tree");
216             }
217             return null;
218         }
219     }
220 }