KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > http > HttpDataObjsServlet


1 /*
2   Copyright (C) 2003 Know Gate S.L. All rights reserved.
3                       C/Oņa, 107 1š2 28050 Madrid (Spain)
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.http;
34
35 import java.lang.reflect.InvocationTargetException JavaDoc;
36
37 import java.io.IOException JavaDoc;
38
39 import java.util.Properties JavaDoc;
40 import java.util.Enumeration JavaDoc;
41 import java.util.HashMap JavaDoc;
42
43 import java.text.SimpleDateFormat JavaDoc;
44 import java.text.ParseException JavaDoc;
45
46 import java.sql.SQLException JavaDoc;
47
48 import javax.servlet.*;
49 import javax.servlet.http.*;
50
51 import com.knowgate.debug.DebugFile;
52 import com.knowgate.debug.StackTraceUtil;
53 import com.knowgate.jdc.JDCConnection;
54 import com.knowgate.dataobjs.DB;
55 import com.knowgate.dataobjs.DBBind;
56 import com.knowgate.dataobjs.DBColumn;
57 import com.knowgate.dataobjs.DBPersist;
58 import com.knowgate.dataobjs.DBSubset;
59 import com.knowgate.misc.Environment;
60 import com.knowgate.misc.Gadgets;
61 import com.knowgate.acl.ACL;
62 import com.knowgate.acl.ACLUser;
63 import com.knowgate.workareas.WorkArea;
64
65 /**
66  * @author Sergio Montoro Ten
67  * @version 3.0
68  */

69
70 public class HttpDataObjsServlet extends HttpServlet {
71
72   private static HashMap JavaDoc oBindings;
73   private static HashMap JavaDoc oWorkAreas;
74
75   public HttpDataObjsServlet() {
76     oBindings = new HashMap JavaDoc();
77     oWorkAreas = new HashMap JavaDoc();
78
79   }
80
81   // ---------------------------------------------------------------------------
82

83   private static synchronized boolean isUserAllowed(JDCConnection oCon, String JavaDoc sUser, String JavaDoc sWrkA)
84       throws SQLException JavaDoc {
85
86       if (DebugFile.trace) {
87         DebugFile.writeln("Begin HttpDataObjsServlet.isUserAllowed("+sUser+","+sWrkA+")");
88         DebugFile.incIdent();
89       }
90
91       HashMap JavaDoc oUserMap = (HashMap JavaDoc) oWorkAreas.get(sWrkA);
92       if (null==oUserMap) {
93         oUserMap = new HashMap JavaDoc();
94         oWorkAreas.put(sWrkA, oUserMap);
95       }
96       Boolean JavaDoc oAllowed = (Boolean JavaDoc) oUserMap.get(sUser);
97       if (null==oAllowed) {
98         oAllowed = new Boolean JavaDoc(WorkArea.isAdmin(oCon, sWrkA, sUser) ||
99                                WorkArea.isPowerUser(oCon, sWrkA, sUser) ||
100                                WorkArea.isUser(oCon, sWrkA, sUser));
101         oUserMap.put(sUser, oAllowed);
102       }
103
104       if (DebugFile.trace) {
105         DebugFile.decIdent();
106         DebugFile.writeln("End HttpDataObjsServlet.isUserAllowed() : " +
107                           String.valueOf(oAllowed.booleanValue()));
108       }
109
110       return oAllowed.booleanValue();
111   } // isUserAllowed
112

113   // ---------------------------------------------------------------------------
114

115   public void doGet(HttpServletRequest request, HttpServletResponse response)
116     throws IOException JavaDoc, ServletException {
117
118     String JavaDoc sCmd = request.getParameter("command");
119
120     if (sCmd.equalsIgnoreCase("update")) {
121       response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Command " + sCmd + " only allowed for POST method");
122       return;
123     }
124
125     if (!sCmd.equalsIgnoreCase("ping") && !sCmd.equalsIgnoreCase("query")) {
126       response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Command " + sCmd + " not recognized");
127       return;
128     }
129
130     if (sCmd.equalsIgnoreCase("ping")) {
131       response.setContentType("text/plain");
132       response.getOutputStream().print("HttpDataObjsServlet ping OK");
133     } else if (sCmd.equalsIgnoreCase("query")){
134       doPost(request, response);
135     }
136
137   } // doGet
138

139   // ---------------------------------------------------------------------------
140

141   public void doPost(HttpServletRequest request, HttpServletResponse response)
142      throws IOException JavaDoc, ServletException {
143
144      DBBind oBnd = null;
145      JDCConnection oCon = null;
146
147      short iAuth;
148      boolean bAllowed;
149      String JavaDoc sDbb = request.getParameter("profile");
150      String JavaDoc sUsr = request.getParameter("user");
151      String JavaDoc sPwd = request.getParameter("password");
152      String JavaDoc sCmd = request.getParameter("command");
153      String JavaDoc sCls = request.getParameter("class");
154      String JavaDoc sTbl = request.getParameter("table");
155      String JavaDoc sFld = request.getParameter("fields");
156      String JavaDoc sWhr = request.getParameter("where");
157      String JavaDoc sMax = request.getParameter("maxrows");
158      String JavaDoc sSkp = request.getParameter("skip");
159      String JavaDoc sCol = request.getParameter("coldelim");
160      String JavaDoc sRow = request.getParameter("rowdelim");
161
162      if (DebugFile.trace) {
163        DebugFile.writeln("Begin HttpDataObjsServlet.doPost()");
164        DebugFile.incIdent();
165      }
166
167      if (null==sDbb) {
168        sDbb = "hipergate";
169      }
170      if (null==sUsr) {
171        if (DebugFile.trace) DebugFile.decIdent();
172        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter user is requiered");
173        return;
174      }
175      if (null==sPwd) {
176        if (DebugFile.trace) DebugFile.decIdent();
177        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter password is requiered");
178        return;
179      }
180      if (null==sCmd) {
181        if (DebugFile.trace) DebugFile.decIdent();
182        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter command is requiered");
183        return;
184      }
185      if (null==sTbl) {
186        if (DebugFile.trace) DebugFile.decIdent();
187        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter table is requiered");
188        return;
189      }
190
191      Properties JavaDoc oEnv = Environment.getProfile(sDbb);
192
193      if (null==oEnv) {
194        if (DebugFile.trace) DebugFile.decIdent();
195        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Databind " + sDbb + " is not available");
196        return;
197      }
198
199      if (!sCmd.equalsIgnoreCase("ping") && !sCmd.equalsIgnoreCase("query") && !sCmd.equalsIgnoreCase("update")) {
200        if (DebugFile.trace) DebugFile.decIdent();
201        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Command " + sCmd + " not recognized");
202        return;
203      }
204
205      if (sCmd.equalsIgnoreCase("ping")) {
206        response.setContentType("text/plain");
207        response.getOutputStream().print("HttpDataObjsServlet ping OK");
208        if (DebugFile.trace) {
209          DebugFile.decIdent();
210          DebugFile.writeln("End HttpDataObjsServlet.doPost()");
211        }
212        return;
213      }
214
215      if (oBindings.containsKey(sDbb)) {
216        oBnd = (DBBind) oBindings.get(sDbb);
217      } else {
218        oBnd = new DBBind(sDbb);
219        oBindings.put(sDbb, oBnd);
220      }
221
222      if (sCmd.equalsIgnoreCase("query")) {
223        int iMax;
224        if (null==sMax)
225          iMax = 500;
226        else
227          iMax = Integer.parseInt(sMax);
228        int iSkp;
229        if (null==sSkp)
230          iSkp = 0;
231        else
232          iSkp = Integer.parseInt(sSkp);
233        DBSubset oDbs = new DBSubset (sTbl, sFld, sWhr, iMax);
234        if (null!=sRow) oDbs.setRowDelimiter(sRow);
235        if (null!=sCol) oDbs.setColumnDelimiter(sCol);
236        oDbs.setMaxRows(iMax);
237        try {
238          oCon = oBnd.getConnection("HttpDataObjsServlet");
239          if (null==oCon) {
240            if (DebugFile.trace) DebugFile.decIdent();
241            throw new ServletException("ERROR Unable to get database connection from pool "+sDbb);
242          }
243          if (Gadgets.checkEMail(sUsr)) {
244            sUsr = ACLUser.getIdFromEmail(oCon, sUsr);
245            if (null==sUsr)
246              iAuth = ACL.USER_NOT_FOUND;
247            else
248              iAuth = ACL.autenticate(oCon, sUsr, sPwd, ACL.PWD_CLEAR_TEXT);
249          } else {
250            iAuth = ACL.autenticate(oCon, sUsr, sPwd, ACL.PWD_CLEAR_TEXT);
251          }
252          switch (iAuth) {
253            case ACL.ACCOUNT_CANCELLED:
254              response.sendError(HttpServletResponse.SC_FORBIDDEN, "Account cancelled");
255              break;
256            case ACL.ACCOUNT_DEACTIVATED:
257              response.sendError(HttpServletResponse.SC_FORBIDDEN, "Account deactivated");
258              break;
259            case ACL.INVALID_PASSWORD:
260              response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid password");
261              break;
262            case ACL.PASSWORD_EXPIRED:
263              response.sendError(HttpServletResponse.SC_FORBIDDEN, "Password expired");
264              break;
265            case ACL.USER_NOT_FOUND:
266              response.sendError(HttpServletResponse.SC_FORBIDDEN, "User not found");
267              break;
268            default:
269              oDbs.load(oCon, iSkp);
270              response.setContentType("text/plain");
271              response.setCharacterEncoding("UTF-8");
272              response.getOutputStream().write(oDbs.toString().getBytes("UTF-8"));
273          }
274          oCon.close("HttpDataObjsServlet");
275          oCon = null;
276        } catch (SQLException JavaDoc sqle) {
277          if (null!=oCon) {
278            try { oCon.close("HttpDataObjsServlet"); } catch (Exception JavaDoc ignore) {}
279            oCon = null;
280          }
281          if (DebugFile.trace) DebugFile.decIdent();
282          throw new ServletException("SQLException "+sqle.getMessage());
283        }
284      }
285      else if (sCmd.equalsIgnoreCase("update")) {
286        if (DebugFile.trace) DebugFile.writeln("command is update");
287        Enumeration JavaDoc oParamNames = request.getParameterNames();
288        DBPersist oDbp;
289        Class JavaDoc oCls;
290        if (null==sCls) {
291          oDbp = new DBPersist(sTbl, "DBPersist");
292          try {
293            oCls = Class.forName("com.knowgate.dataobjs.DBPersist");
294          } catch (ClassNotFoundException JavaDoc neverthrown) { oCls=null; }
295        } else {
296          try {
297            oCls = Class.forName(sCls);
298            oDbp = (DBPersist) oCls.newInstance();
299          } catch (ClassNotFoundException JavaDoc nfe) {
300            if (DebugFile.trace) DebugFile.decIdent();
301            throw new ServletException("ClassCastException "+nfe.getMessage()+" "+sCls);
302          } catch (InstantiationException JavaDoc ine) {
303            if (DebugFile.trace) DebugFile.decIdent();
304            throw new ServletException("ClassCastException "+ine.getMessage()+" "+sCls);
305          } catch (IllegalAccessException JavaDoc iae) {
306            if (DebugFile.trace) DebugFile.decIdent();
307            throw new ServletException("ClassCastException "+iae.getMessage()+" "+sCls);
308          } catch (ClassCastException JavaDoc cce) {
309            if (DebugFile.trace) DebugFile.decIdent();
310            throw new ServletException("ClassCastException "+cce.getMessage()+" "+sCls);
311          }
312        }
313        if (DebugFile.trace) DebugFile.writeln("class "+oDbp.getClass().getName()+" instantiated");
314        while (oParamNames.hasMoreElements()) {
315          String JavaDoc sKey = (String JavaDoc) oParamNames.nextElement();
316          if (DebugFile.trace) DebugFile.writeln("reading parameter "+sKey);
317          sKey = sKey.trim();
318          int iSpc = sKey.indexOf(' ');
319          if (iSpc>0) {
320            String JavaDoc sKeyName = sKey.substring(0, iSpc);
321            iSpc++;
322            if (iSpc<sKey.length()-1) {
323              String JavaDoc sSQLType = sKey.substring(iSpc);
324              if (DebugFile.trace) DebugFile.writeln("sqltype is "+sSQLType);
325              if (sSQLType.toUpperCase().startsWith("DATE") || sSQLType.toUpperCase().startsWith("DATETIME") || sSQLType.toUpperCase().startsWith("TIMESTAMP")) {
326                iSpc = sSQLType.indexOf(' ');
327                String JavaDoc sDtFmt = "";
328                try {
329                  if (iSpc > 0) {
330                    sDtFmt = sSQLType.substring(++iSpc);
331                    if (DebugFile.trace) DebugFile.writeln("date format is "+sDtFmt);
332                    oDbp.put(sKeyName, request.getParameter(sKey), new SimpleDateFormat JavaDoc(sDtFmt));
333                  } else {
334                    oDbp.put(sKeyName, request.getParameter(sKey), DBColumn.getSQLType(sSQLType));
335                  }
336                } catch (ParseException JavaDoc pe) {
337                  if (DebugFile.trace) DebugFile.decIdent();
338                  throw new ServletException("ERROR ParseException "+sKey+"|"+sDtFmt+"|"+request.getParameter(sKey)+" "+pe.getMessage());
339                } catch (IllegalArgumentException JavaDoc ia) {
340                  if (DebugFile.trace) DebugFile.decIdent();
341                  throw new ServletException("ERROR IllegalArgumentException "+sKey+"|"+sDtFmt+"|"+request.getParameter(sKey)+ia.getMessage());
342                }
343              } else {
344                try {
345                  oDbp.put(sKeyName, request.getParameter(sKey), DBColumn.getSQLType(sSQLType));
346                } catch (NumberFormatException JavaDoc nfe) {
347                  if (DebugFile.trace) DebugFile.decIdent();
348                  throw new ServletException("ERROR NumberFormatException "+sKey+" "+" "+request.getParameter(sKey)+" "+nfe.getMessage());
349                }
350              }
351            } else {
352              oDbp.put(sKeyName, request.getParameter(sKey));
353            }
354          } else {
355            oDbp.put(sKey, request.getParameter(sKey));
356          }
357        } // wend
358
try {
359          oCon = oBnd.getConnection("HttpDataObjsServlet");
360          if (null==oCon) {
361            if (DebugFile.trace) DebugFile.decIdent();
362            throw new ServletException("ERROR Unable to get database connection from pool "+sDbb);
363          }
364          if (Gadgets.checkEMail(sUsr)) {
365            sUsr = ACLUser.getIdFromEmail(oCon, sUsr);
366            if (null==sUsr)
367              iAuth = ACL.USER_NOT_FOUND;
368            else
369              iAuth = ACL.autenticate(oCon, sUsr, sPwd, ACL.PWD_CLEAR_TEXT);
370          } else {
371            iAuth = ACL.autenticate(oCon, sUsr, sPwd, ACL.PWD_CLEAR_TEXT);
372          }
373          switch (iAuth) {
374            case ACL.ACCOUNT_CANCELLED:
375              response.sendError(HttpServletResponse.SC_FORBIDDEN, "Account cancelled");
376              break;
377            case ACL.ACCOUNT_DEACTIVATED:
378              response.sendError(HttpServletResponse.SC_FORBIDDEN, "Account deactivated");
379              break;
380            case ACL.INVALID_PASSWORD:
381              response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid password");
382              break;
383            case ACL.PASSWORD_EXPIRED:
384              response.sendError(HttpServletResponse.SC_FORBIDDEN, "Password expired");
385              break;
386            case ACL.USER_NOT_FOUND:
387              response.sendError(HttpServletResponse.SC_FORBIDDEN, "User not found");
388              break;
389            default:
390              if (oDbp.isNull(DB.gu_workarea))
391                bAllowed = true;
392              else
393                bAllowed = isUserAllowed(oCon, sUsr, oDbp.getString(DB.gu_workarea));
394                if (bAllowed) {
395                  oCon.setAutoCommit(true);
396                  if (null==sCls) {
397                    oDbp.store(oCon);
398                  } else {
399                    if (DebugFile.trace) DebugFile.writeln(oCls.getName()+".getMethod(\"store\", new Class[]{Class.forName(\"com.knowgate.jdc.JDCConnection\")}).invoke(...)");
400                    oCls.getMethod("store", new Class JavaDoc[]{Class.forName("com.knowgate.jdc.JDCConnection")}).invoke(oDbp, new Object JavaDoc[]{oCon});
401                  }
402                  response.setContentType("text/plain");
403                  response.setCharacterEncoding("UTF-8");
404                  response.getOutputStream().print("SUCCESS");
405                } else {
406                  response.sendError(HttpServletResponse.SC_FORBIDDEN, "User does not have write permissions on target WorkArea");
407                }
408          } // end switch
409
oCon.close("HttpDataObjsServlet");
410          oCon = null;
411        } catch (InvocationTargetException JavaDoc ite) {
412          if (null!=oCon) {
413            try { oCon.close("HttpDataObjsServlet"); oCon = null;
414            } catch (Exception JavaDoc ignore) {}
415          } // fi
416
if (DebugFile.trace) DebugFile.decIdent();
417          throw new ServletException(ite.getCause().getClass().getName()+" "+ite.getCause().getMessage()+"\n"+StackTraceUtil.getStackTrace(ite));
418        } catch (Exception JavaDoc xcpt) {
419          if (null!=oCon) {
420            try { oCon.close("HttpDataObjsServlet"); oCon = null;
421            } catch (Exception JavaDoc ignore) {}
422          } // fi
423
if (DebugFile.trace) DebugFile.decIdent();
424          throw new ServletException(xcpt.getClass().getName()+" "+xcpt.getMessage()+"\n"+StackTraceUtil.getStackTrace(xcpt));
425        }
426      } // fi
427
if (DebugFile.trace) {
428        DebugFile.decIdent();
429        DebugFile.writeln("End HttpDataObjsServlet.doPost()");
430      }
431   } // doPost
432

433   // ---------------------------------------------------------------------------
434
}
435
Popular Tags