KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derby > drda > NetServlet


1 /*
2
3    Derby - Class org.apache.derby.drda.NetServlet
4
5    Licensed to the Apache Software Foundation (ASF) under one or more
6    contributor license agreements. See the NOTICE file distributed with
7    this work for additional information regarding copyright ownership.
8    The ASF licenses this file to You under the Apache License, Version 2.0
9    (the "License"); you may not use this file except in compliance with
10    the License. You may obtain a copy of the License at
11
12       http://www.apache.org/licenses/LICENSE-2.0
13
14    Unless required by applicable law or agreed to in writing, software
15    distributed under the License is distributed on an "AS IS" BASIS,
16    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17    See the License for the specific language governing permissions and
18    limitations under the License.
19
20  */

21
22 package org.apache.derby.drda;
23
24 import java.io.*;
25 import java.util.*;
26
27 import java.net.*;
28
29 import java.security.AccessController JavaDoc;
30 import java.security.PrivilegedExceptionAction JavaDoc;
31
32 import javax.servlet.*;
33 import javax.servlet.http.*;
34
35 import org.apache.derby.iapi.tools.i18n.LocalizedResource;
36 import org.apache.derby.iapi.reference.Property;
37
38 /**
39     This servlet can be used to start Derby Network Server from a remote location.
40     <P>
41     These servlet configuration parameters are understood by this servlet.
42     <UL>
43     <LI><PRE>portNumber</PRE> - Port number to use. The default is 1527.
44     <LI><PRE>startNetworkServerOnInit</PRE> - Starts the Derby Network Server at servlet
45             initialization if 'true'.
46     <LI><PRE>tracingDirectory</PRE> - Directory for trace files
47     </UL>
48
49 */

50 public class NetServlet extends HttpServlet {
51     private final static int MAX_CONNECT_TRYS = 20;
52     private final static String JavaDoc SERVLET_PROP_MESSAGES = "org.apache.derby.loc.drda.servlet";
53     private final static String JavaDoc SERVLET_ADDRESS = "derbynet";
54
55     private String JavaDoc formHeader = null;
56     private String JavaDoc host = "localhost";
57     private int portNumber=1527;
58     private String JavaDoc tracingDirectory;
59     private boolean logStatus= false; /* Logging off */
60     private boolean traceStatus = false; /* Tracing off */
61     private String JavaDoc[] knownLang = {"cs","en","es","de_DE","fr","hu","it",
62             "ja_JP","ko_KR","pl","pt_BR","ru","zh_CN","zh_TW"};
63     private String JavaDoc locale;
64
65     private final static int NOT_GIVEN = -2;
66     private final static int INVALID = -3;
67
68     private NetworkServerControl server;
69     private PrintWriter out;
70
71     // for doPri block
72
private Runnable JavaDoc service;
73     
74     /**
75         Initialize the servlet.
76         Configuration parameters:
77         <UL>
78         <LI><PRE>portNumber</PRE> - Port number
79         <LI><PRE>traceDirectory</PRE> - location of trace directory
80         <LI><PRE>startNetworkServerOnInit</PRE> - start the server on initialization
81         </UL>
82     */

83     public void init(ServletConfig config)
84         throws ServletException
85     {
86         
87         LocalizedResource langUtil = new LocalizedResource(null,null,SERVLET_PROP_MESSAGES);
88                 
89         String JavaDoc port = config.getInitParameter("portNumber");
90         if (port != null) {
91             int p = Integer.valueOf(port).intValue();
92             if (p > 0)
93                 portNumber = p;
94         }
95
96         this.tracingDirectory = config.getInitParameter("tracingDirectory");
97         
98         if ( this.tracingDirectory == null ) {
99             this.tracingDirectory = "";
100         }
101
102         String JavaDoc startup = config.getInitParameter("startNetworkServerOnInit");
103
104         // test if the server is already running
105
try {
106             //don't send output to console
107
if (server == null) {
108                 server = new NetworkServerControl(InetAddress.getByName(host), portNumber);
109                 // assert this.tracingDirectory != null
110
if ( ! this.tracingDirectory.trim().equals("")) {
111                     server.setTraceDirectory(this.tracingDirectory);
112                 }
113             }
114             
115             if (isServerStarted(server,1))
116                 return;
117         } catch (Exception JavaDoc e) {}
118
119         if (startup != null) {
120             boolean start = Boolean.valueOf(startup).booleanValue();
121             if (start)
122             {
123                 runServer(langUtil, null, null);
124                 return;
125             }
126         }
127     }
128
129     /**
130         Get the form of NetServlet. Provides buttons and forms to control the
131         Network server.
132     */

133     public void doGet (HttpServletRequest request, HttpServletResponse response)
134             throws ServletException, IOException
135     {
136         String JavaDoc logOnMessage;
137         String JavaDoc logOffMessage;
138         String JavaDoc traceOnMessage;
139         String JavaDoc traceOffMessage;
140         String JavaDoc traceOnOffMessage;
141         String JavaDoc startMessage;
142         String JavaDoc stopMessage;
143         String JavaDoc returnMessage;
144         String JavaDoc traceSessionMessage;
145         String JavaDoc traceDirMessage;
146         String JavaDoc contMessage;
147         String JavaDoc setParamMessage;
148         String JavaDoc setParamMessage2;
149         String JavaDoc netParamMessage;
150         LocalizedResource langUtil;
151         
152         langUtil = getCurrentAppUI(request);
153         response.setContentType("text/html; charset=UTF-8");
154         
155         //prevent caching of the servlet since contents can change - beetle 4649
156
response.setHeader("Cache-Control", "no-cache,no-store");
157
158         formHeader = "<form enctype='multipart/form-data; charset=UTF-8' action='" +
159             request.getRequestURI() +" '>";
160
161         out = new PrintWriter(new
162             OutputStreamWriter(response.getOutputStream(), "UTF8"),true);
163         
164         //inialize messages
165
logOnMessage = escapeSingleQuotes(langUtil.getTextMessage("SRV_LogOn"));
166         logOffMessage = escapeSingleQuotes(langUtil.getTextMessage("SRV_LogOff"));
167         traceOnMessage = escapeSingleQuotes(langUtil.getTextMessage("SRV_TraceOn"));
168         traceOffMessage = escapeSingleQuotes(langUtil.getTextMessage("SRV_TraceOff"));
169         startMessage = escapeSingleQuotes(langUtil.getTextMessage("SRV_Start"));
170         stopMessage = escapeSingleQuotes(langUtil.getTextMessage("SRV_Stop"));
171         traceSessionMessage = escapeSingleQuotes(langUtil.getTextMessage("SRV_TraceSessButton"));
172         traceOnOffMessage = escapeSingleQuotes(langUtil.getTextMessage("SRV_TraceOnOff"));
173         returnMessage = escapeSingleQuotes(langUtil.getTextMessage("SRV_Return"));
174         traceDirMessage = escapeSingleQuotes(langUtil.getTextMessage("SRV_TraceDir"));
175         contMessage = escapeSingleQuotes(langUtil.getTextMessage("SRV_Continue"));
176         setParamMessage = escapeSingleQuotes(langUtil.getTextMessage("SRV_SetParam"));
177         setParamMessage2 = escapeSingleQuotes(langUtil.getTextMessage("SRV_SetParam2"));
178         netParamMessage = escapeSingleQuotes(langUtil.getTextMessage("SRV_NetParam"));
179
180         printBanner(langUtil);
181         // set up a server we can use
182
if (server == null) {
183             try {
184                 server = new NetworkServerControl();
185             }catch (Exception JavaDoc e) {
186                 printErrorForm(langUtil, request, e, returnMessage);
187                 return;
188             }
189         }
190         server.setClientLocale(locale);
191         String JavaDoc form = getForm(request);
192         String JavaDoc doAction = getDoAction(request);
193         // if doAction is set, use it to determine form
194
if (doAction != null )
195         {
196             if (doAction.equals(traceOnOffMessage))
197                 form = traceSessionMessage;
198             else
199                 form = doAction;
200         }
201         // if no form, determine form based on server status
202
boolean serverStatus = getServerStatus();
203         if (form == null)
204         {
205             if (serverStatus)
206                 form = startMessage;
207             else
208                 form = stopMessage;
209         }
210         else if (form.equals(startMessage))
211         {
212             if (!serverStatus) {
213                 runServer(langUtil, request, returnMessage);
214             }
215         }
216         else if (form.equals(stopMessage))
217         {
218             if (serverStatus) {
219                 shutdownServer(langUtil, request, returnMessage);
220             }
221             setDefaults();
222                     
223         }
224         else if (form.equals(returnMessage) || form.equals(returnMessage))
225         {
226             // check if server is still running and use that to determine which form
227
if (serverStatus)
228             {
229                 form = startMessage;
230             }
231             else
232             {
233                 form = stopMessage;
234             }
235         }
236
237         out.println( formHeader);
238         // display forms
239

240         form = escapeSingleQuotes(form);
241         doAction = escapeSingleQuotes(doAction);
242         if (form.equals(startMessage))
243         {
244             String JavaDoc logButton = getLogging(request);
245             String JavaDoc traceButton = getTrace(request);
246             if (logButton != null && logButton.equals(logOnMessage))
247             {
248                 if (logging(langUtil, true, request, returnMessage))
249                     logStatus = true;
250             }
251             if (logButton != null && logButton.equals(logOffMessage))
252             {
253                 if (logging(langUtil, false, request, returnMessage))
254                     logStatus = false;
255             }
256             if (traceButton != null && traceButton.equals(traceOnMessage))
257             {
258                 if (traceAll(langUtil, true, request, returnMessage))
259                     traceStatus = true;
260             }
261             if (traceButton != null && traceButton.equals(traceOffMessage))
262             {
263                 if (traceAll(langUtil, false, request, returnMessage))
264                     traceStatus = false;
265             }
266             displayCurrentStatus(request, langUtil, returnMessage);
267             out.println( "<h4>"+langUtil.getTextMessage("SRV_StopButton")+"</h4>" );
268             out.println( "<INPUT type=submit name=form value='"+ stopMessage + "'>" );
269
270             out.println( "<h4>"+langUtil.getTextMessage("SRV_LogButton2")+"</h4>" );
271
272             if (logStatus)
273             {
274                 out.println( "<INPUT type=submit name=logform value='"+logOffMessage + "'>" );
275             }
276             else
277             {
278                 out.println( "<INPUT type=submit name=logform value='"+logOnMessage + "'>" );
279             }
280             out.println( "<h4>"+langUtil.getTextMessage("SRV_TraceButton2")+"</h4>" );
281             if (traceStatus)
282             {
283                 out.println( "<INPUT type=submit name=traceform value='"+traceOffMessage+ "'>" );
284             }
285             else
286             {
287                 out.println( "<INPUT type=submit name=traceform value='"+traceOnMessage + "'>" );
288             }
289
290             out.println( "<h4>"+langUtil.getTextMessage("SRV_TraceSession")+"</h4>" );
291             out.println( "<INPUT type=submit name=form value='"+ traceSessionMessage + "'>" );
292             out.println( "<h4>"+langUtil.getTextMessage("SRV_TraceDirButton")+"</h4>" );
293             out.println( "<INPUT type=submit name=form value='"+ traceDirMessage + "'>" );
294             out.println( "<h4>"+langUtil.getTextMessage("SRV_ThreadButton")+"</h4>" );
295             out.println( "<INPUT type=submit name=form value='"+ netParamMessage+ "'>" );
296         }
297         else if (form.equals(stopMessage))
298         {
299
300             printAsContentHeader(langUtil.getTextMessage("SRV_NotStarted"));
301             String JavaDoc logButton = getLogging(request);
302             String JavaDoc traceButton = getTrace(request);
303             if (logButton != null && logButton.equals(logOnMessage))
304                 logStatus = true;
305             if (logButton != null && logButton.equals(logOffMessage))
306                 logStatus = false;
307             if (traceButton != null && traceButton.equals(traceOnMessage))
308                 traceStatus = true;
309             if (traceButton != null && traceButton.equals(traceOffMessage))
310                 traceStatus = false;
311             if (logStatus)
312             {
313                 out.println( "<h4>"+langUtil.getTextMessage("SRV_LogOffButton")+"</h4>" );
314                 out.println( "<INPUT type=submit name=logform value='"+logOffMessage + "'>" );
315             }
316             else
317             {
318                 out.println( "<h4>"+langUtil.getTextMessage("SRV_LogOnButton")+"</h4>" );
319                 out.println( "<INPUT type=submit name=logform value='"+logOnMessage + "'>" );
320             }
321             if (traceStatus)
322             {
323                 out.println( "<h4>"+langUtil.getTextMessage("SRV_TraceOffButton")+"</h4>" );
324                 out.println( "<INPUT type=submit name=traceform value='"+traceOffMessage + "'>" );
325             }
326             else
327             {
328                 out.println( "<h4>"+langUtil.getTextMessage("SRV_TraceOnButton")+"</h4>" );
329                 out.println( "<INPUT type=submit name=traceform value='"+traceOnMessage + "'>" );
330             }
331             out.println( "<h4>"+langUtil.getTextMessage("SRV_StartButton")+"</h4>" );
332             out.println( "<INPUT type=submit name=form value='"+startMessage+ "'>" );
333         }
334         else if (form.equals(traceSessionMessage))
335         {
336             if (doAction != null)
337             {
338                 if (doAction.equals(traceOnOffMessage))
339                 {
340                     String JavaDoc sessionid = request.getParameter("sessionid");
341                     int session = 0;
342                     try {
343                         session = (new Integer JavaDoc(sessionid)).intValue();
344                     } catch (Exception JavaDoc e) {
345                         printErrorForm(langUtil, request,
346                             langUtil.getTextMessage("SRV_InvalidVal",
347                             sessionid, langUtil.getTextMessage("SRV_SessionID")),
348                             returnMessage);
349                         return;
350                     }
351                     Properties p = null;
352                     try {
353                         p = server.getCurrentProperties();
354                     } catch (Exception JavaDoc e) {
355                         printErrorForm(langUtil, request, e, returnMessage);
356                         return;
357                     }
358                     // if it's on, turn it off, if its off, turn it on
359
boolean val;
360                     if (p.getProperty(Property.DRDA_PROP_TRACE+sessionid) != null)
361                         val = false;
362                     else
363                         val = true;
364                     if (traceSession(langUtil, val, session, request, returnMessage))
365                     {
366                         if (val)
367                             out.println( "<h4>"+langUtil.getTextMessage("SRV_StatusTraceNoOn", sessionid)+"</h4>");
368                         else
369                             out.println( "<h4>"+langUtil.getTextMessage("SRV_StatusTraceNoOff", sessionid)+"</h4>");
370                     }
371                     else
372                         return;
373                         
374                 }
375             }
376             printAsContentHeader(langUtil.getTextMessage("SRV_TraceSessButton"));
377             out.println( "<h4>" + getHtmlLabelledMessageInstance(langUtil,
378                 "SRV_SessionID", "sessionId") + "</h4>");
379             out.println( "<INPUT type=text name=sessionid size=10 maxlength=10 " +
380                 "id='sessionId' value=''>");
381             out.println( "<h4> </h4>");
382             out.println( "<INPUT type=submit name=doaction value='"+traceOnOffMessage+ "'>" );
383             out.println( "<INPUT type=submit name=form value='"+returnMessage+ "'>" );
384         }
385         else if (form.equals(traceDirMessage))
386         {
387             boolean set = false;
388             String JavaDoc traceDirectory = null;
389             printAsContentHeader(traceDirMessage);
390             if (doAction != null)
391             {
392                 if (doAction.equals(traceDirMessage))
393                 {
394                     traceDirectory = getParam(request, "tracedirectory");
395                     if (traceDirectory(langUtil, traceDirectory, request,
396                             returnMessage) )
397                         set = true;
398                     else
399                         return;
400                     
401                 }
402             }
403             if (set)
404             {
405                 out.println( "<h2>"+langUtil.getTextMessage("SRV_TraceDirDone", traceDirectory)+"</h2>");
406                 out.println( "<INPUT type=submit name=form value='"+returnMessage+"'>" );
407             }
408             else
409             {
410                 out.println( "<h4>" + getHtmlLabelledMessageInstance(langUtil,
411                     "SRV_TraceDir", "tracedir") + "</h4>");
412                 out.println( "<INPUT type=text name=tracedirectory size=60 maxlength=256 " +
413                     "id='tracedir' value='"+tracingDirectory+"'>");
414                 out.println( "<h4> </h4>");
415                 out.println( "<INPUT type=submit name=doaction value='"+traceDirMessage+ "'>" );
416                 out.println( "<INPUT type=submit name=form value='"+returnMessage+ "'>" );
417             }
418         }
419         else if (form.equals(netParamMessage))
420         {
421             int maxThreads = 0;
422             int timeSlice = 0;
423             String JavaDoc maxName = langUtil.getTextMessage("SRV_NewMaxThreads");
424             String JavaDoc sliceName = langUtil.getTextMessage("SRV_NewTimeSlice");
425             try {
426                 Properties p = server.getCurrentProperties();
427                 String JavaDoc val = p.getProperty(Property.DRDA_PROP_MAXTHREADS);
428                 maxThreads= (new Integer JavaDoc(val)).intValue();
429                 val = p.getProperty(Property.DRDA_PROP_TIMESLICE);
430                 timeSlice= (new Integer JavaDoc(val)).intValue();
431             } catch (Exception JavaDoc e) {
432                 printErrorForm(langUtil, request, e, returnMessage);
433                 return;
434             }
435             if (doAction != null && doAction.equals(netParamMessage))
436             {
437                 int newMaxThreads = getIntParameter(request, "newmaxthreads",
438                     "SRV_NewMaxThreads", langUtil, returnMessage);
439                 int newTimeSlice = (newMaxThreads == INVALID) ? NOT_GIVEN :
440                     getIntParameter(request, "newtimeslice", "SRV_NewTimeSlice", langUtil,
441                         returnMessage);
442                 if ((newMaxThreads == INVALID) || (newTimeSlice == INVALID))
443                     return;
444                 else if (!(newMaxThreads == NOT_GIVEN && newTimeSlice == NOT_GIVEN))
445                 {
446                     if (newMaxThreads != NOT_GIVEN)
447                         maxThreads = newMaxThreads;
448                     if (newTimeSlice != NOT_GIVEN)
449                         timeSlice = newTimeSlice;
450                     if (!setNetParam(langUtil, maxThreads, timeSlice, request,
451                             returnMessage))
452                         return;
453                 }
454             }
455             
456             out.println(formHeader);
457             printAsContentHeader(netParamMessage);
458             out.println( "<h4>"+langUtil.getTextMessage("SRV_MaxThreads", new Integer JavaDoc(maxThreads).toString()) +"</h4>");
459             out.println( "<h4>"+langUtil.getTextMessage("SRV_TimeSlice", new Integer JavaDoc(timeSlice).toString()) +"</h4>");
460             out.println( "<h4> </h4>");
461             out.println( "<h4> <label for='newmaxthreads'>"+maxName+"</label> </h4>");
462             out.println( "<INPUT type=text name=newmaxthreads size=10 maxlength=10 " +
463                 "id='newmaxthreads' value=''>" );
464             out.println( "<h4> <label for='newslice'>"+sliceName+"</label> </h4>");
465             out.println( "<INPUT type=text name=newtimeslice size=10 maxlength=10 " +
466                 "id='newslice' value=''>" );
467             out.println( "<h4> </h4>");
468             out.println( "<INPUT type=submit name=doaction value='"+netParamMessage+ "'>" );
469             out.println( "<INPUT type=submit name=form value='"+returnMessage+ "'>" );
470         }
471         else
472         {
473             System.out.println("Internal Error: Unknown form, "+ form);
474             out.println("Internal Error: Unknown form, "+ form);
475
476
477         }
478
479         out.println( "</html>" );
480         out.println( "</body>" );
481
482     }
483
484     /**
485         Get the form of NetServlet. Provides a buttons and form to control the
486         Network server
487
488     */

489     public void doPost (HttpServletRequest request, HttpServletResponse response)
490             throws ServletException, IOException
491     {
492         // simply call the doGet()
493
doGet(request, response);
494     }
495
496     private String JavaDoc getForm(HttpServletRequest request) throws java.io.IOException JavaDoc{
497         return getParam(request, "form");
498     }
499     private String JavaDoc getDoAction(HttpServletRequest request) throws java.io.IOException JavaDoc {
500         return getParam(request, "doaction");
501     }
502     private String JavaDoc getLogging(HttpServletRequest request) throws java.io.IOException JavaDoc {
503         return getParam(request, "logform");
504     }
505     private String JavaDoc getTrace(HttpServletRequest request) throws java.io.IOException JavaDoc {
506         return getParam(request, "traceform");
507     }
508
509     /**
510      * get UTF8 parameter value and decode international characters
511      * @param request HttpServletRequest
512      * @param paramName Parameter name
513      * @return decoded String
514      */

515     private String JavaDoc getParam(HttpServletRequest request, String JavaDoc paramName) throws
516     java.io.IOException JavaDoc {
517                 
518         String JavaDoc newValue= null;
519         String JavaDoc value = request.getParameter(paramName);
520         if (value == null)
521             return value;
522         newValue = new String JavaDoc(value.getBytes("ISO-8859-1"),"UTF8");
523         return newValue;
524     }
525
526     /**
527      * Start the network server and attempt to connect to it before
528      * returning
529      *
530      * @param localUtil LocalizedResource to use to translate messages
531      * @param request HttpServetRequest for error forms
532      * @param returnMessage localized continue message for continue button on error form
533      * @exception ServletException throws an exception if error in starting the
534      * Network Server during initialization
535      */

536     private void runServer(LocalizedResource localUtil, HttpServletRequest request,
537         String JavaDoc returnMessage)
538         throws ServletException
539     {
540         service = new Runnable JavaDoc() {
541             public void run() {
542                 try {
543                     //Echo server output to console
544
NetworkServerControl runserver = new
545                         NetworkServerControl(InetAddress.getByName(host),
546                                              portNumber);
547                     runserver.start(null);
548                 }
549                 catch (Exception JavaDoc e) {
550                     throw new RuntimeException JavaDoc(e.getMessage());
551                 }
552             }
553         };
554         Thread JavaDoc servThread = null;
555         try {
556             servThread = (Thread JavaDoc) AccessController.doPrivileged(
557                                 new PrivilegedExceptionAction JavaDoc() {
558                                     public Object JavaDoc run() throws Exception JavaDoc
559                                     {
560                                         return new Thread JavaDoc(service);
561                                     }
562                                 }
563                             );
564         }
565         catch (Exception JavaDoc e) {
566             throw new RuntimeException JavaDoc(e.getMessage());
567         }
568         servThread.start();
569
570         // try to connect to server
571
try {
572             boolean connectWorked = false;
573             int t = 0;
574             do
575             {
576                 t++;
577                 try {
578                         Thread.sleep(100);
579                 } catch (InterruptedException JavaDoc ie) {
580                     throw new ServletException(localUtil.getTextMessage("SRV_Interupt"));
581                 }
582                 try {
583                     if (isServerStarted(server,1))
584                         connectWorked = true;
585                 } catch (Exception JavaDoc e) {} //ignore error we'll just try again
586

587             }while (!connectWorked && t < MAX_CONNECT_TRYS);
588             if (t >= MAX_CONNECT_TRYS)
589                 throw new Exception JavaDoc(localUtil.getTextMessage("SRV_MaxTrys",
590                     new Integer JavaDoc(MAX_CONNECT_TRYS).toString()));
591             // turn logging on if required
592
if (logStatus)
593                 server.logConnections(true);
594             // turn tracing on
595
if (traceStatus)
596                 server.trace(true);
597         }catch (Exception JavaDoc e) {
598             if (out != null)
599                 printErrorForm(localUtil, request, e, returnMessage);
600             else
601                 throw new ServletException(e.getMessage());
602         }
603     }
604     /**
605      * Display an error form
606      *
607      * @param localUtil LocalizedResource to use to translate messages
608      * @param request HttpServetRequest for error forms
609      * @param e Exception to be displayed
610      * @param returnMessage localized continue message for continue button on error form
611      */

612     private void printErrorForm(LocalizedResource localUtil, HttpServletRequest request,
613         Exception JavaDoc e, String JavaDoc returnMessage)
614     {
615         printAsContentHeader(localUtil.getTextMessage("SRV_NetworkServerError"));
616         out.println( "<h4>"+localUtil.getTextMessage("SRV_Message", e.getMessage()) + "</h4>" );
617         out.println( "<INPUT type=submit name=form value='"+returnMessage+"'>" );
618         out.println( "</html>" );
619         out.println( "</body>" );
620     }
621     /**
622      * Display an error form
623      *
624      * @param localUtil LocalizedResource to use to translate messages
625      * @param request HttpServetRequest for error forms
626      * @param msg String to be displayed
627      * @param returnMessage localized continue message for continue button on error form
628      */

629     private void printErrorForm(LocalizedResource localUtil, HttpServletRequest request,
630         String JavaDoc msg, String JavaDoc returnMessage)
631     {
632         printAsContentHeader(localUtil.getTextMessage("SRV_NetworkServerError"));
633         out.println( "<h4>"+localUtil.getTextMessage("SRV_Message", msg) + "</h4>" );
634         out.println( "<INPUT type=submit name=form value='"+returnMessage+"'>" );
635         out.println( "</html>" );
636         out.println( "</body>" );
637     }
638     /**
639      * Display the current Network server status
640      *
641      * @param request HttpServetRequest for forms
642      * @param localUtil LocalizedResource to use for localizing messages
643      * @param returnMessage localized continue message for continue button on error form
644      */

645     private void displayCurrentStatus(HttpServletRequest request,
646         LocalizedResource localUtil, String JavaDoc returnMessage)
647     {
648         try {
649
650             printAsContentHeader(localUtil.getTextMessage("SRV_Started"));
651             Properties p = server.getCurrentProperties();
652             String JavaDoc val = p.getProperty(Property.DRDA_PROP_LOGCONNECTIONS);
653             if (val.equals("true"))
654                 logStatus = true;
655             else
656                 logStatus = false;
657             if (logStatus)
658                 out.println( "<h4>"+localUtil.getTextMessage("SRV_StatusLogOn")+"</h4>");
659             else
660                 out.println( "<h4>"+localUtil.getTextMessage("SRV_StatusLogOff")+"</h4>");
661             val = p.getProperty(Property.DRDA_PROP_TRACEALL);
662             if (val.equals("true"))
663                 traceStatus = true;
664             else
665                 traceStatus = false;
666             if (traceStatus)
667                 out.println( "<h4>"+localUtil.getTextMessage("SRV_StatusTraceOn")+"</h4>");
668             else
669                 out.println( "<h4>"+localUtil.getTextMessage("SRV_StatusTraceOff")+"</h4>");
670             val = p.getProperty(Property.DRDA_PROP_PORTNUMBER);
671             out.println( "<h4>"+localUtil.getTextMessage("SRV_PortNumber", val)+"</h4>");
672             
673         }
674         catch (Exception JavaDoc e) {
675             printErrorForm(localUtil, request, e, returnMessage);
676         }
677     }
678     /**
679      * Get the currrent server status by using test connection
680      *
681      * @return true if server is up and reachable; false; otherwise
682      */

683     private boolean getServerStatus()
684     {
685         try {
686             
687             if (isServerStarted(server,1))
688                 return true;
689         } catch (Exception JavaDoc e) {}
690         return false;
691     }
692     /**
693      * Shutdown the network server
694      *
695      * @param localUtil LocalizedResource to use to translate messages
696      * @param request HttpServetRequest for forms
697      * @param returnMessage localized continue message for continue button on error form
698      * @return true if succeeded; false; otherwise
699      */

700     private boolean shutdownServer(LocalizedResource localUtil,
701         HttpServletRequest request, String JavaDoc returnMessage)
702     {
703         boolean retval = false;
704         try {
705             server.shutdown();
706             retval = true;
707         } catch (Exception JavaDoc e)
708         {
709             printErrorForm(localUtil, request, e, returnMessage);
710         }
711         return retval;
712     }
713     /**
714      * Turn logging of connections on
715      *
716      * @param localUtil LocalizedResource to use to translate messages
717      * @param request HttpServetRequest for forms
718      * @param returnMessage localized continue message for continue button on error form
719      * @return true if succeeded; false; otherwise
720      */

721     private boolean logging(LocalizedResource localUtil, boolean val,
722         HttpServletRequest request, String JavaDoc returnMessage)
723     {
724         boolean retval = false;
725         try {
726             server.logConnections(val);
727             retval = true;
728         } catch (Exception JavaDoc e)
729         {
730             printErrorForm(localUtil, request, e, returnMessage);
731         }
732         return retval;
733     }
734     /**
735      * Change tracing for all sessions
736      *
737      * @param localUtil LocalizedResource to use to translate messages
738      * @param val if true, turn tracing on, if false turn it off
739      * @param request HttpServetRequest for forms
740      * @param returnMessage localized continue message for continue button on error form
741      * @return true if succeeded; false; otherwise
742      */

743     private boolean traceAll(LocalizedResource localUtil, boolean val,
744         HttpServletRequest request, String JavaDoc returnMessage)
745     {
746         boolean retval = false;
747         try {
748             server.trace(val);
749             retval = true;
750         } catch (Exception JavaDoc e)
751         {
752             printErrorForm(localUtil, request, e, returnMessage);
753         }
754         return retval;
755     }
756     /**
757      * Change tracing for a given session
758      *
759      * @param localUtil LocalizedResource to use to translate messages
760      * @param val if true, turn tracing on, if false turn it off
761      * @param session session to trace
762      * @param request HttpServetRequest for forms
763      * @param returnMessage localized continue message for continue button on error form
764      * @return true if succeeded; false; otherwise
765      */

766     private boolean traceSession(LocalizedResource localUtil, boolean val, int session,
767         HttpServletRequest request, String JavaDoc returnMessage)
768     {
769         boolean retval = false;
770         try {
771             server.trace(session, val);
772             retval = true;
773         } catch (Exception JavaDoc e)
774         {
775             printErrorForm(localUtil, request, e, returnMessage);
776         }
777         return retval;
778     }
779
780     /**
781      * Set trace directory
782      *
783      * @param localUtil LocalizedResource to use to translate messages
784      * @param traceDirectory directory for trace files
785      * @param request HttpServetRequest for forms
786      * @param returnMessage localized continue message for continue
787      * button on error form
788      * @return true if succeeded; false; otherwise
789      */

790     private boolean traceDirectory(LocalizedResource localUtil, String JavaDoc traceDirectory,
791         HttpServletRequest request, String JavaDoc returnMessage)
792     {
793         boolean retval = false;
794
795         if ((traceDirectory == null) || traceDirectory.equals("")) {
796             printErrorForm(localUtil, request,
797                 localUtil.getTextMessage("SRV_MissingParam",
798                 localUtil.getTextMessage("SRV_TraceDir")), returnMessage);
799
800             return retval;
801         }
802
803         try {
804             this.tracingDirectory = traceDirectory;
805             server.setTraceDirectory(traceDirectory);
806             retval = true;
807         } catch (Exception JavaDoc e)
808         {
809             printErrorForm(localUtil, request, e, returnMessage);
810         }
811         return retval;
812     }
813
814     /**
815      * Set Network server parameters
816      *
817      * @param localUtil LocalizedResource to use to translate messages
818      * @param max maximum number of threads
819      * @param slice time slice for each connection
820      * @param request HttpServetRequest for forms
821      * @param returnMessage localized continue message for continue
822      * button on error form
823      * @return true if succeeded; false; otherwise
824      */

825     private boolean setNetParam(LocalizedResource localUtil, int max, int slice,
826         HttpServletRequest request, String JavaDoc returnMessage)
827     {
828         boolean retval = false;
829
830         try {
831             server.setMaxThreads(max);
832             server.setTimeSlice(slice);
833             retval = true;
834         } catch (Exception JavaDoc e)
835         {
836             printErrorForm(localUtil, request, e, returnMessage);
837         }
838         return retval;
839     }
840
841
842     /**
843      * Set defaults for logging and tracing (both off)
844      */

845     private void setDefaults()
846     {
847         logStatus = false;
848         traceStatus = false;
849     }
850     /**
851      * Get an integer parameter
852      *
853      * @param request HttpServetRequest for forms
854      * @param name parameter name
855      * @param fieldKey Key for the name of the field we're reading.
856      * @param localUtil LocalizedResource to use in localizing messages
857      * @param returnMessage localized continue message for continue
858      * button on error form
859      */

860     private int getIntParameter(HttpServletRequest request,
861             String JavaDoc name, String JavaDoc fieldKey, LocalizedResource localUtil, String JavaDoc returnMessage)
862     {
863         String JavaDoc val = request.getParameter(name);
864         int retval;
865         if (val == null || val.equals(""))
866             return NOT_GIVEN;
867         try {
868             retval = (new Integer JavaDoc(val)).intValue();
869         } catch (Exception JavaDoc e) {
870             printErrorForm(localUtil, request,localUtil.getTextMessage("SRV_InvalidVal",
871                 val, localUtil.getTextMessage(fieldKey)), returnMessage);
872             return INVALID;
873         }
874         if (retval < 0) {
875         // negative integers not allowed for the parameters we're getting.
876
printErrorForm(localUtil, request, localUtil.getTextMessage("SRV_InvalidVal",
877                 val, localUtil.getTextMessage(fieldKey)), returnMessage);
878             return INVALID;
879         }
880         return retval;
881     }
882     /**
883      * Print Derby Network Server banner
884      */

885     private void printBanner(LocalizedResource localUtil)
886     {
887         out.println("<a HREF=\"#navskip\">[ " +
888         localUtil.getTextMessage("SRV_SkipToContent") + " ]</a>");
889         out.println(" - <a HREF=\"" + SERVLET_ADDRESS + "\">[ " +
890         localUtil.getTextMessage("SRV_BackToMain") + " ]</a>");
891         out.println( "<html>" );
892         out.println( "<title>"+localUtil.getTextMessage("SRV_Banner")+"</title>" );
893         out.println( "<body>" );
894         out.println( "<hr>" );
895         out.println( "<h1>"+localUtil.getTextMessage("SRV_Banner")+"</h1>" );
896         out.println( "<hr>" );
897
898     }
899     /**
900      * Determine the locale file needed for this browsers preferences
901      * Defaults to the settings for derby.locale and derby.codeset if set
902      * English otherwise if browsers preferences can't be found
903      *
904      * @param request HttpServetRequest for forms
905      * @return the appUI which fits the browsers preferences
906      */

907     private LocalizedResource getCurrentAppUI(HttpServletRequest request)
908     {
909         LocalizedResource localUtil;
910         String JavaDoc acceptLanguage = request.getHeader("Accept-Language");
911         localUtil = new LocalizedResource(null,null,SERVLET_PROP_MESSAGES);
912         // if no language specified use one set by derby.locale, derby.codeset
913
locale = null;
914         if (acceptLanguage == null)
915         {
916             return localUtil;
917         }
918         // Use a tokenizer ot separate acceptable languages
919
StringTokenizer tokenizer = new StringTokenizer(acceptLanguage, ",");
920         while (tokenizer.hasMoreTokens())
921         {
922             //Get the next acceptable language
923
String JavaDoc lang = tokenizer.nextToken();
924             lang = getLocStringFromLanguage(lang);
925             int langindex = translationAvailable(lang);
926             // have we found one
927
if (langindex != -1)
928             {
929                 localUtil.init(null, lang, SERVLET_PROP_MESSAGES);
930                 // locale will be passed to server, server routines will get set appropriately
931
locale = lang;
932                 return localUtil;
933             }
934         }
935         // nothing worked use defaults
936
return localUtil;
937         
938     }
939     /**
940      * Get locale string from language which may have qvalue set
941      *
942      * @param lang language string to parse
943      *
944      * @return stripped language string to use in matching
945      */

946     private String JavaDoc getLocStringFromLanguage(String JavaDoc lang)
947     {
948         int semi;
949         // Cut off any q-value that might come after a semi-colon
950
if ((semi = lang.indexOf(';')) != -1)
951         {
952             lang = lang.substring(0, semi);
953         }
954         // trim any whitespace and fix the code, as some browsers might send a bad format
955
lang = fixLanguageCode(lang.trim());
956         return lang;
957     }
958     /**
959      * Check if the required translation is available
960      *
961      * @param lang language we are looking for
962      *
963      * @return index into language array if found, -1 otherwise;
964      */

965     private int translationAvailable(String JavaDoc lang)
966     {
967         // assert lang == fixLanguageCode(lang)
968
// we don't need to use toUpperCase() anymore, as the lang is already fixed
969
for (int i = 0; i < knownLang.length; i++)
970             if (knownLang[i].equals(lang))
971                 return i;
972         return -1;
973     }
974     
975     /**
976      * Fix the language code, as some browsers send then in a bad format (for instance,
977      * Firefox sends en-us instead of en_US).
978      *
979      * @param lang language to be fixed
980      *
981      * @return fixed version of the language, with _ separating parts and country in upper case
982      */

983     private String JavaDoc fixLanguageCode( String JavaDoc lang ) {
984         int index = lang.indexOf('-');
985         if ( index != -1 ) {
986             return fixLanguageCode( lang, index );
987         }
988         index = lang.indexOf('_');
989         if ( index != -1 ) {
990             return fixLanguageCode( lang, index );
991         }
992         return lang;
993     }
994
995     private String JavaDoc fixLanguageCode(String JavaDoc lang, int index) {
996         return lang.substring(0,index) + "_" + lang.substring(index+1).toUpperCase(Locale.ENGLISH);
997     }
998
999     /**
1000     * get an HTML labelled message from the resource bundle file, according to
1001     * the given key.
1002     */

1003    public String JavaDoc getHtmlLabelledMessageInstance(LocalizedResource localUtil, String JavaDoc key, String JavaDoc id) {
1004
1005        if (id == null)
1006            id = "";
1007
1008        return ("<label for='" + id + "'>" + localUtil.getTextMessage(key) +
1009            "</label>");
1010
1011    }
1012
1013    /**
1014     * Print the received string as a header.
1015     * @param str The string to be printed as a header.
1016     */

1017    private void printAsContentHeader(String JavaDoc str) {
1018
1019        out.println("<a name=\"navskip\"></a><h2>" + str + "</h2>");
1020        return;
1021
1022    }
1023
1024    /**
1025     * If the received string has one or more single quotes
1026     * in it, replace each one with the HTML escape-code
1027     * for a single quote (apostrophe) so that the string
1028     * can be properly displayed on a submit button.
1029     * @param str The string in which we want to escape
1030     * single quotes.
1031     */

1032    private String JavaDoc escapeSingleQuotes(String JavaDoc str) {
1033
1034        if ((str == null) || (str.indexOf("'") < 0))
1035            return str;
1036
1037        char [] cA = str.toCharArray();
1038
1039        // Worst (and extremely unlikely) case is every
1040
// character is a single quote, which means the
1041
// escaped string would need to be 4 times as long.
1042
char [] result = new char[4*cA.length];
1043
1044        int j = 0;
1045        for (int i = 0; i < cA.length; i++) {
1046
1047            if (cA[i] == '\'') {
1048                result[j++] = '&';
1049                result[j++] = '#';
1050                result[j++] = '3';
1051                result[j++] = '9';
1052            }
1053            else
1054                result[j++] = cA[i];
1055
1056        }
1057
1058        return new String JavaDoc(result, 0, j);
1059
1060    }
1061
1062    private static boolean isServerStarted(NetworkServerControl server, int ntries)
1063    {
1064        for (int i = 1; i <= ntries; i ++)
1065        {
1066            try {
1067                Thread.sleep(500);
1068                server.ping();
1069                return true;
1070            }
1071            catch (Exception JavaDoc e) {
1072                if (i == ntries)
1073                    return false;
1074            }
1075        }
1076        return false;
1077    }
1078    
1079}
1080
Popular Tags