0001: /*
0002:
0003: Derby - Class org.apache.derby.drda.NetServlet
0004:
0005: Licensed to the Apache Software Foundation (ASF) under one or more
0006: contributor license agreements. See the NOTICE file distributed with
0007: this work for additional information regarding copyright ownership.
0008: The ASF licenses this file to You under the Apache License, Version 2.0
0009: (the "License"); you may not use this file except in compliance with
0010: the License. You may obtain a copy of the License at
0011:
0012: http://www.apache.org/licenses/LICENSE-2.0
0013:
0014: Unless required by applicable law or agreed to in writing, software
0015: distributed under the License is distributed on an "AS IS" BASIS,
0016: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0017: See the License for the specific language governing permissions and
0018: limitations under the License.
0019:
0020: */
0021:
0022: package org.apache.derby.drda;
0023:
0024: import java.io.*;
0025: import java.util.*;
0026:
0027: import java.net.*;
0028:
0029: import java.security.AccessController;
0030: import java.security.PrivilegedExceptionAction;
0031:
0032: import javax.servlet.*;
0033: import javax.servlet.http.*;
0034:
0035: import org.apache.derby.iapi.tools.i18n.LocalizedResource;
0036: import org.apache.derby.iapi.reference.Property;
0037:
0038: /**
0039: This servlet can be used to start Derby Network Server from a remote location.
0040: <P>
0041: These servlet configuration parameters are understood by this servlet.
0042: <UL>
0043: <LI><PRE>portNumber</PRE> - Port number to use. The default is 1527.
0044: <LI><PRE>startNetworkServerOnInit</PRE> - Starts the Derby Network Server at servlet
0045: initialization if 'true'.
0046: <LI><PRE>tracingDirectory</PRE> - Directory for trace files
0047: </UL>
0048:
0049: */
0050: public class NetServlet extends HttpServlet {
0051: private final static int MAX_CONNECT_TRYS = 20;
0052: private final static String SERVLET_PROP_MESSAGES = "org.apache.derby.loc.drda.servlet";
0053: private final static String SERVLET_ADDRESS = "derbynet";
0054:
0055: private String formHeader = null;
0056: private String host = "localhost";
0057: private int portNumber = 1527;
0058: private String tracingDirectory;
0059: private boolean logStatus = false; /* Logging off */
0060: private boolean traceStatus = false; /* Tracing off */
0061: private String[] knownLang = { "cs", "en", "es", "de_DE", "fr",
0062: "hu", "it", "ja_JP", "ko_KR", "pl", "pt_BR", "ru", "zh_CN",
0063: "zh_TW" };
0064: private String locale;
0065:
0066: private final static int NOT_GIVEN = -2;
0067: private final static int INVALID = -3;
0068:
0069: private NetworkServerControl server;
0070: private PrintWriter out;
0071:
0072: // for doPri block
0073: private Runnable service;
0074:
0075: /**
0076: Initialize the servlet.
0077: Configuration parameters:
0078: <UL>
0079: <LI><PRE>portNumber</PRE> - Port number
0080: <LI><PRE>traceDirectory</PRE> - location of trace directory
0081: <LI><PRE>startNetworkServerOnInit</PRE> - start the server on initialization
0082: </UL>
0083: */
0084: public void init(ServletConfig config) throws ServletException {
0085:
0086: LocalizedResource langUtil = new LocalizedResource(null, null,
0087: SERVLET_PROP_MESSAGES);
0088:
0089: String port = config.getInitParameter("portNumber");
0090: if (port != null) {
0091: int p = Integer.valueOf(port).intValue();
0092: if (p > 0)
0093: portNumber = p;
0094: }
0095:
0096: this .tracingDirectory = config
0097: .getInitParameter("tracingDirectory");
0098:
0099: if (this .tracingDirectory == null) {
0100: this .tracingDirectory = "";
0101: }
0102:
0103: String startup = config
0104: .getInitParameter("startNetworkServerOnInit");
0105:
0106: // test if the server is already running
0107: try {
0108: //don't send output to console
0109: if (server == null) {
0110: server = new NetworkServerControl(InetAddress
0111: .getByName(host), portNumber);
0112: // assert this.tracingDirectory != null
0113: if (!this .tracingDirectory.trim().equals("")) {
0114: server.setTraceDirectory(this .tracingDirectory);
0115: }
0116: }
0117:
0118: if (isServerStarted(server, 1))
0119: return;
0120: } catch (Exception e) {
0121: }
0122:
0123: if (startup != null) {
0124: boolean start = Boolean.valueOf(startup).booleanValue();
0125: if (start) {
0126: runServer(langUtil, null, null);
0127: return;
0128: }
0129: }
0130: }
0131:
0132: /**
0133: Get the form of NetServlet. Provides buttons and forms to control the
0134: Network server.
0135: */
0136: public void doGet(HttpServletRequest request,
0137: HttpServletResponse response) throws ServletException,
0138: IOException {
0139: String logOnMessage;
0140: String logOffMessage;
0141: String traceOnMessage;
0142: String traceOffMessage;
0143: String traceOnOffMessage;
0144: String startMessage;
0145: String stopMessage;
0146: String returnMessage;
0147: String traceSessionMessage;
0148: String traceDirMessage;
0149: String contMessage;
0150: String setParamMessage;
0151: String setParamMessage2;
0152: String netParamMessage;
0153: LocalizedResource langUtil;
0154:
0155: langUtil = getCurrentAppUI(request);
0156: response.setContentType("text/html; charset=UTF-8");
0157:
0158: //prevent caching of the servlet since contents can change - beetle 4649
0159: response.setHeader("Cache-Control", "no-cache,no-store");
0160:
0161: formHeader = "<form enctype='multipart/form-data; charset=UTF-8' action='"
0162: + request.getRequestURI() + " '>";
0163:
0164: out = new PrintWriter(new OutputStreamWriter(response
0165: .getOutputStream(), "UTF8"), true);
0166:
0167: //inialize messages
0168: logOnMessage = escapeSingleQuotes(langUtil
0169: .getTextMessage("SRV_LogOn"));
0170: logOffMessage = escapeSingleQuotes(langUtil
0171: .getTextMessage("SRV_LogOff"));
0172: traceOnMessage = escapeSingleQuotes(langUtil
0173: .getTextMessage("SRV_TraceOn"));
0174: traceOffMessage = escapeSingleQuotes(langUtil
0175: .getTextMessage("SRV_TraceOff"));
0176: startMessage = escapeSingleQuotes(langUtil
0177: .getTextMessage("SRV_Start"));
0178: stopMessage = escapeSingleQuotes(langUtil
0179: .getTextMessage("SRV_Stop"));
0180: traceSessionMessage = escapeSingleQuotes(langUtil
0181: .getTextMessage("SRV_TraceSessButton"));
0182: traceOnOffMessage = escapeSingleQuotes(langUtil
0183: .getTextMessage("SRV_TraceOnOff"));
0184: returnMessage = escapeSingleQuotes(langUtil
0185: .getTextMessage("SRV_Return"));
0186: traceDirMessage = escapeSingleQuotes(langUtil
0187: .getTextMessage("SRV_TraceDir"));
0188: contMessage = escapeSingleQuotes(langUtil
0189: .getTextMessage("SRV_Continue"));
0190: setParamMessage = escapeSingleQuotes(langUtil
0191: .getTextMessage("SRV_SetParam"));
0192: setParamMessage2 = escapeSingleQuotes(langUtil
0193: .getTextMessage("SRV_SetParam2"));
0194: netParamMessage = escapeSingleQuotes(langUtil
0195: .getTextMessage("SRV_NetParam"));
0196:
0197: printBanner(langUtil);
0198: // set up a server we can use
0199: if (server == null) {
0200: try {
0201: server = new NetworkServerControl();
0202: } catch (Exception e) {
0203: printErrorForm(langUtil, request, e, returnMessage);
0204: return;
0205: }
0206: }
0207: server.setClientLocale(locale);
0208: String form = getForm(request);
0209: String doAction = getDoAction(request);
0210: // if doAction is set, use it to determine form
0211: if (doAction != null) {
0212: if (doAction.equals(traceOnOffMessage))
0213: form = traceSessionMessage;
0214: else
0215: form = doAction;
0216: }
0217: // if no form, determine form based on server status
0218: boolean serverStatus = getServerStatus();
0219: if (form == null) {
0220: if (serverStatus)
0221: form = startMessage;
0222: else
0223: form = stopMessage;
0224: } else if (form.equals(startMessage)) {
0225: if (!serverStatus) {
0226: runServer(langUtil, request, returnMessage);
0227: }
0228: } else if (form.equals(stopMessage)) {
0229: if (serverStatus) {
0230: shutdownServer(langUtil, request, returnMessage);
0231: }
0232: setDefaults();
0233:
0234: } else if (form.equals(returnMessage)
0235: || form.equals(returnMessage)) {
0236: // check if server is still running and use that to determine which form
0237: if (serverStatus) {
0238: form = startMessage;
0239: } else {
0240: form = stopMessage;
0241: }
0242: }
0243:
0244: out.println(formHeader);
0245: // display forms
0246:
0247: form = escapeSingleQuotes(form);
0248: doAction = escapeSingleQuotes(doAction);
0249: if (form.equals(startMessage)) {
0250: String logButton = getLogging(request);
0251: String traceButton = getTrace(request);
0252: if (logButton != null && logButton.equals(logOnMessage)) {
0253: if (logging(langUtil, true, request, returnMessage))
0254: logStatus = true;
0255: }
0256: if (logButton != null && logButton.equals(logOffMessage)) {
0257: if (logging(langUtil, false, request, returnMessage))
0258: logStatus = false;
0259: }
0260: if (traceButton != null
0261: && traceButton.equals(traceOnMessage)) {
0262: if (traceAll(langUtil, true, request, returnMessage))
0263: traceStatus = true;
0264: }
0265: if (traceButton != null
0266: && traceButton.equals(traceOffMessage)) {
0267: if (traceAll(langUtil, false, request, returnMessage))
0268: traceStatus = false;
0269: }
0270: displayCurrentStatus(request, langUtil, returnMessage);
0271: out.println("<h4>"
0272: + langUtil.getTextMessage("SRV_StopButton")
0273: + "</h4>");
0274: out.println("<INPUT type=submit name=form value='"
0275: + stopMessage + "'>");
0276:
0277: out.println("<h4>"
0278: + langUtil.getTextMessage("SRV_LogButton2")
0279: + "</h4>");
0280:
0281: if (logStatus) {
0282: out.println("<INPUT type=submit name=logform value='"
0283: + logOffMessage + "'>");
0284: } else {
0285: out.println("<INPUT type=submit name=logform value='"
0286: + logOnMessage + "'>");
0287: }
0288: out.println("<h4>"
0289: + langUtil.getTextMessage("SRV_TraceButton2")
0290: + "</h4>");
0291: if (traceStatus) {
0292: out.println("<INPUT type=submit name=traceform value='"
0293: + traceOffMessage + "'>");
0294: } else {
0295: out.println("<INPUT type=submit name=traceform value='"
0296: + traceOnMessage + "'>");
0297: }
0298:
0299: out.println("<h4>"
0300: + langUtil.getTextMessage("SRV_TraceSession")
0301: + "</h4>");
0302: out.println("<INPUT type=submit name=form value='"
0303: + traceSessionMessage + "'>");
0304: out.println("<h4>"
0305: + langUtil.getTextMessage("SRV_TraceDirButton")
0306: + "</h4>");
0307: out.println("<INPUT type=submit name=form value='"
0308: + traceDirMessage + "'>");
0309: out.println("<h4>"
0310: + langUtil.getTextMessage("SRV_ThreadButton")
0311: + "</h4>");
0312: out.println("<INPUT type=submit name=form value='"
0313: + netParamMessage + "'>");
0314: } else if (form.equals(stopMessage)) {
0315:
0316: printAsContentHeader(langUtil
0317: .getTextMessage("SRV_NotStarted"));
0318: String logButton = getLogging(request);
0319: String traceButton = getTrace(request);
0320: if (logButton != null && logButton.equals(logOnMessage))
0321: logStatus = true;
0322: if (logButton != null && logButton.equals(logOffMessage))
0323: logStatus = false;
0324: if (traceButton != null
0325: && traceButton.equals(traceOnMessage))
0326: traceStatus = true;
0327: if (traceButton != null
0328: && traceButton.equals(traceOffMessage))
0329: traceStatus = false;
0330: if (logStatus) {
0331: out.println("<h4>"
0332: + langUtil.getTextMessage("SRV_LogOffButton")
0333: + "</h4>");
0334: out.println("<INPUT type=submit name=logform value='"
0335: + logOffMessage + "'>");
0336: } else {
0337: out.println("<h4>"
0338: + langUtil.getTextMessage("SRV_LogOnButton")
0339: + "</h4>");
0340: out.println("<INPUT type=submit name=logform value='"
0341: + logOnMessage + "'>");
0342: }
0343: if (traceStatus) {
0344: out.println("<h4>"
0345: + langUtil.getTextMessage("SRV_TraceOffButton")
0346: + "</h4>");
0347: out.println("<INPUT type=submit name=traceform value='"
0348: + traceOffMessage + "'>");
0349: } else {
0350: out.println("<h4>"
0351: + langUtil.getTextMessage("SRV_TraceOnButton")
0352: + "</h4>");
0353: out.println("<INPUT type=submit name=traceform value='"
0354: + traceOnMessage + "'>");
0355: }
0356: out.println("<h4>"
0357: + langUtil.getTextMessage("SRV_StartButton")
0358: + "</h4>");
0359: out.println("<INPUT type=submit name=form value='"
0360: + startMessage + "'>");
0361: } else if (form.equals(traceSessionMessage)) {
0362: if (doAction != null) {
0363: if (doAction.equals(traceOnOffMessage)) {
0364: String sessionid = request
0365: .getParameter("sessionid");
0366: int session = 0;
0367: try {
0368: session = (new Integer(sessionid)).intValue();
0369: } catch (Exception e) {
0370: printErrorForm(
0371: langUtil,
0372: request,
0373: langUtil
0374: .getTextMessage(
0375: "SRV_InvalidVal",
0376: sessionid,
0377: langUtil
0378: .getTextMessage("SRV_SessionID")),
0379: returnMessage);
0380: return;
0381: }
0382: Properties p = null;
0383: try {
0384: p = server.getCurrentProperties();
0385: } catch (Exception e) {
0386: printErrorForm(langUtil, request, e,
0387: returnMessage);
0388: return;
0389: }
0390: // if it's on, turn it off, if its off, turn it on
0391: boolean val;
0392: if (p.getProperty(Property.DRDA_PROP_TRACE
0393: + sessionid) != null)
0394: val = false;
0395: else
0396: val = true;
0397: if (traceSession(langUtil, val, session, request,
0398: returnMessage)) {
0399: if (val)
0400: out.println("<h4>"
0401: + langUtil.getTextMessage(
0402: "SRV_StatusTraceNoOn",
0403: sessionid) + "</h4>");
0404: else
0405: out.println("<h4>"
0406: + langUtil.getTextMessage(
0407: "SRV_StatusTraceNoOff",
0408: sessionid) + "</h4>");
0409: } else
0410: return;
0411:
0412: }
0413: }
0414: printAsContentHeader(langUtil
0415: .getTextMessage("SRV_TraceSessButton"));
0416: out.println("<h4>"
0417: + getHtmlLabelledMessageInstance(langUtil,
0418: "SRV_SessionID", "sessionId") + "</h4>");
0419: out
0420: .println("<INPUT type=text name=sessionid size=10 maxlength=10 "
0421: + "id='sessionId' value=''>");
0422: out.println("<h4> </h4>");
0423: out.println("<INPUT type=submit name=doaction value='"
0424: + traceOnOffMessage + "'>");
0425: out.println("<INPUT type=submit name=form value='"
0426: + returnMessage + "'>");
0427: } else if (form.equals(traceDirMessage)) {
0428: boolean set = false;
0429: String traceDirectory = null;
0430: printAsContentHeader(traceDirMessage);
0431: if (doAction != null) {
0432: if (doAction.equals(traceDirMessage)) {
0433: traceDirectory = getParam(request, "tracedirectory");
0434: if (traceDirectory(langUtil, traceDirectory,
0435: request, returnMessage))
0436: set = true;
0437: else
0438: return;
0439:
0440: }
0441: }
0442: if (set) {
0443: out.println("<h2>"
0444: + langUtil.getTextMessage("SRV_TraceDirDone",
0445: traceDirectory) + "</h2>");
0446: out.println("<INPUT type=submit name=form value='"
0447: + returnMessage + "'>");
0448: } else {
0449: out.println("<h4>"
0450: + getHtmlLabelledMessageInstance(langUtil,
0451: "SRV_TraceDir", "tracedir") + "</h4>");
0452: out
0453: .println("<INPUT type=text name=tracedirectory size=60 maxlength=256 "
0454: + "id='tracedir' value='"
0455: + tracingDirectory + "'>");
0456: out.println("<h4> </h4>");
0457: out.println("<INPUT type=submit name=doaction value='"
0458: + traceDirMessage + "'>");
0459: out.println("<INPUT type=submit name=form value='"
0460: + returnMessage + "'>");
0461: }
0462: } else if (form.equals(netParamMessage)) {
0463: int maxThreads = 0;
0464: int timeSlice = 0;
0465: String maxName = langUtil
0466: .getTextMessage("SRV_NewMaxThreads");
0467: String sliceName = langUtil
0468: .getTextMessage("SRV_NewTimeSlice");
0469: try {
0470: Properties p = server.getCurrentProperties();
0471: String val = p
0472: .getProperty(Property.DRDA_PROP_MAXTHREADS);
0473: maxThreads = (new Integer(val)).intValue();
0474: val = p.getProperty(Property.DRDA_PROP_TIMESLICE);
0475: timeSlice = (new Integer(val)).intValue();
0476: } catch (Exception e) {
0477: printErrorForm(langUtil, request, e, returnMessage);
0478: return;
0479: }
0480: if (doAction != null && doAction.equals(netParamMessage)) {
0481: int newMaxThreads = getIntParameter(request,
0482: "newmaxthreads", "SRV_NewMaxThreads", langUtil,
0483: returnMessage);
0484: int newTimeSlice = (newMaxThreads == INVALID) ? NOT_GIVEN
0485: : getIntParameter(request, "newtimeslice",
0486: "SRV_NewTimeSlice", langUtil,
0487: returnMessage);
0488: if ((newMaxThreads == INVALID)
0489: || (newTimeSlice == INVALID))
0490: return;
0491: else if (!(newMaxThreads == NOT_GIVEN && newTimeSlice == NOT_GIVEN)) {
0492: if (newMaxThreads != NOT_GIVEN)
0493: maxThreads = newMaxThreads;
0494: if (newTimeSlice != NOT_GIVEN)
0495: timeSlice = newTimeSlice;
0496: if (!setNetParam(langUtil, maxThreads, timeSlice,
0497: request, returnMessage))
0498: return;
0499: }
0500: }
0501:
0502: out.println(formHeader);
0503: printAsContentHeader(netParamMessage);
0504: out.println("<h4>"
0505: + langUtil.getTextMessage("SRV_MaxThreads",
0506: new Integer(maxThreads).toString())
0507: + "</h4>");
0508: out.println("<h4>"
0509: + langUtil.getTextMessage("SRV_TimeSlice",
0510: new Integer(timeSlice).toString())
0511: + "</h4>");
0512: out.println("<h4> </h4>");
0513: out.println("<h4> <label for='newmaxthreads'>" + maxName
0514: + "</label> </h4>");
0515: out
0516: .println("<INPUT type=text name=newmaxthreads size=10 maxlength=10 "
0517: + "id='newmaxthreads' value=''>");
0518: out.println("<h4> <label for='newslice'>" + sliceName
0519: + "</label> </h4>");
0520: out
0521: .println("<INPUT type=text name=newtimeslice size=10 maxlength=10 "
0522: + "id='newslice' value=''>");
0523: out.println("<h4> </h4>");
0524: out.println("<INPUT type=submit name=doaction value='"
0525: + netParamMessage + "'>");
0526: out.println("<INPUT type=submit name=form value='"
0527: + returnMessage + "'>");
0528: } else {
0529: System.out.println("Internal Error: Unknown form, " + form);
0530: out.println("Internal Error: Unknown form, " + form);
0531:
0532: }
0533:
0534: out.println("</html>");
0535: out.println("</body>");
0536:
0537: }
0538:
0539: /**
0540: Get the form of NetServlet. Provides a buttons and form to control the
0541: Network server
0542:
0543: */
0544: public void doPost(HttpServletRequest request,
0545: HttpServletResponse response) throws ServletException,
0546: IOException {
0547: // simply call the doGet()
0548: doGet(request, response);
0549: }
0550:
0551: private String getForm(HttpServletRequest request)
0552: throws java.io.IOException {
0553: return getParam(request, "form");
0554: }
0555:
0556: private String getDoAction(HttpServletRequest request)
0557: throws java.io.IOException {
0558: return getParam(request, "doaction");
0559: }
0560:
0561: private String getLogging(HttpServletRequest request)
0562: throws java.io.IOException {
0563: return getParam(request, "logform");
0564: }
0565:
0566: private String getTrace(HttpServletRequest request)
0567: throws java.io.IOException {
0568: return getParam(request, "traceform");
0569: }
0570:
0571: /**
0572: * get UTF8 parameter value and decode international characters
0573: * @param request HttpServletRequest
0574: * @param paramName Parameter name
0575: * @return decoded String
0576: */
0577: private String getParam(HttpServletRequest request, String paramName)
0578: throws java.io.IOException {
0579:
0580: String newValue = null;
0581: String value = request.getParameter(paramName);
0582: if (value == null)
0583: return value;
0584: newValue = new String(value.getBytes("ISO-8859-1"), "UTF8");
0585: return newValue;
0586: }
0587:
0588: /**
0589: * Start the network server and attempt to connect to it before
0590: * returning
0591: *
0592: * @param localUtil LocalizedResource to use to translate messages
0593: * @param request HttpServetRequest for error forms
0594: * @param returnMessage localized continue message for continue button on error form
0595: * @exception ServletException throws an exception if error in starting the
0596: * Network Server during initialization
0597: */
0598: private void runServer(LocalizedResource localUtil,
0599: HttpServletRequest request, String returnMessage)
0600: throws ServletException {
0601: service = new Runnable() {
0602: public void run() {
0603: try {
0604: //Echo server output to console
0605: NetworkServerControl runserver = new NetworkServerControl(
0606: InetAddress.getByName(host), portNumber);
0607: runserver.start(null);
0608: } catch (Exception e) {
0609: throw new RuntimeException(e.getMessage());
0610: }
0611: }
0612: };
0613: Thread servThread = null;
0614: try {
0615: servThread = (Thread) AccessController
0616: .doPrivileged(new PrivilegedExceptionAction() {
0617: public Object run() throws Exception {
0618: return new Thread(service);
0619: }
0620: });
0621: } catch (Exception e) {
0622: throw new RuntimeException(e.getMessage());
0623: }
0624: servThread.start();
0625:
0626: // try to connect to server
0627: try {
0628: boolean connectWorked = false;
0629: int t = 0;
0630: do {
0631: t++;
0632: try {
0633: Thread.sleep(100);
0634: } catch (InterruptedException ie) {
0635: throw new ServletException(localUtil
0636: .getTextMessage("SRV_Interupt"));
0637: }
0638: try {
0639: if (isServerStarted(server, 1))
0640: connectWorked = true;
0641: } catch (Exception e) {
0642: } //ignore error we'll just try again
0643:
0644: } while (!connectWorked && t < MAX_CONNECT_TRYS);
0645: if (t >= MAX_CONNECT_TRYS)
0646: throw new Exception(localUtil.getTextMessage(
0647: "SRV_MaxTrys", new Integer(MAX_CONNECT_TRYS)
0648: .toString()));
0649: // turn logging on if required
0650: if (logStatus)
0651: server.logConnections(true);
0652: // turn tracing on
0653: if (traceStatus)
0654: server.trace(true);
0655: } catch (Exception e) {
0656: if (out != null)
0657: printErrorForm(localUtil, request, e, returnMessage);
0658: else
0659: throw new ServletException(e.getMessage());
0660: }
0661: }
0662:
0663: /**
0664: * Display an error form
0665: *
0666: * @param localUtil LocalizedResource to use to translate messages
0667: * @param request HttpServetRequest for error forms
0668: * @param e Exception to be displayed
0669: * @param returnMessage localized continue message for continue button on error form
0670: */
0671: private void printErrorForm(LocalizedResource localUtil,
0672: HttpServletRequest request, Exception e,
0673: String returnMessage) {
0674: printAsContentHeader(localUtil
0675: .getTextMessage("SRV_NetworkServerError"));
0676: out.println("<h4>"
0677: + localUtil.getTextMessage("SRV_Message", e
0678: .getMessage()) + "</h4>");
0679: out.println("<INPUT type=submit name=form value='"
0680: + returnMessage + "'>");
0681: out.println("</html>");
0682: out.println("</body>");
0683: }
0684:
0685: /**
0686: * Display an error form
0687: *
0688: * @param localUtil LocalizedResource to use to translate messages
0689: * @param request HttpServetRequest for error forms
0690: * @param msg String to be displayed
0691: * @param returnMessage localized continue message for continue button on error form
0692: */
0693: private void printErrorForm(LocalizedResource localUtil,
0694: HttpServletRequest request, String msg, String returnMessage) {
0695: printAsContentHeader(localUtil
0696: .getTextMessage("SRV_NetworkServerError"));
0697: out.println("<h4>"
0698: + localUtil.getTextMessage("SRV_Message", msg)
0699: + "</h4>");
0700: out.println("<INPUT type=submit name=form value='"
0701: + returnMessage + "'>");
0702: out.println("</html>");
0703: out.println("</body>");
0704: }
0705:
0706: /**
0707: * Display the current Network server status
0708: *
0709: * @param request HttpServetRequest for forms
0710: * @param localUtil LocalizedResource to use for localizing messages
0711: * @param returnMessage localized continue message for continue button on error form
0712: */
0713: private void displayCurrentStatus(HttpServletRequest request,
0714: LocalizedResource localUtil, String returnMessage) {
0715: try {
0716:
0717: printAsContentHeader(localUtil
0718: .getTextMessage("SRV_Started"));
0719: Properties p = server.getCurrentProperties();
0720: String val = p
0721: .getProperty(Property.DRDA_PROP_LOGCONNECTIONS);
0722: if (val.equals("true"))
0723: logStatus = true;
0724: else
0725: logStatus = false;
0726: if (logStatus)
0727: out.println("<h4>"
0728: + localUtil.getTextMessage("SRV_StatusLogOn")
0729: + "</h4>");
0730: else
0731: out.println("<h4>"
0732: + localUtil.getTextMessage("SRV_StatusLogOff")
0733: + "</h4>");
0734: val = p.getProperty(Property.DRDA_PROP_TRACEALL);
0735: if (val.equals("true"))
0736: traceStatus = true;
0737: else
0738: traceStatus = false;
0739: if (traceStatus)
0740: out.println("<h4>"
0741: + localUtil.getTextMessage("SRV_StatusTraceOn")
0742: + "</h4>");
0743: else
0744: out.println("<h4>"
0745: + localUtil
0746: .getTextMessage("SRV_StatusTraceOff")
0747: + "</h4>");
0748: val = p.getProperty(Property.DRDA_PROP_PORTNUMBER);
0749: out.println("<h4>"
0750: + localUtil.getTextMessage("SRV_PortNumber", val)
0751: + "</h4>");
0752:
0753: } catch (Exception e) {
0754: printErrorForm(localUtil, request, e, returnMessage);
0755: }
0756: }
0757:
0758: /**
0759: * Get the currrent server status by using test connection
0760: *
0761: * @return true if server is up and reachable; false; otherwise
0762: */
0763: private boolean getServerStatus() {
0764: try {
0765:
0766: if (isServerStarted(server, 1))
0767: return true;
0768: } catch (Exception e) {
0769: }
0770: return false;
0771: }
0772:
0773: /**
0774: * Shutdown the network server
0775: *
0776: * @param localUtil LocalizedResource to use to translate messages
0777: * @param request HttpServetRequest for forms
0778: * @param returnMessage localized continue message for continue button on error form
0779: * @return true if succeeded; false; otherwise
0780: */
0781: private boolean shutdownServer(LocalizedResource localUtil,
0782: HttpServletRequest request, String returnMessage) {
0783: boolean retval = false;
0784: try {
0785: server.shutdown();
0786: retval = true;
0787: } catch (Exception e) {
0788: printErrorForm(localUtil, request, e, returnMessage);
0789: }
0790: return retval;
0791: }
0792:
0793: /**
0794: * Turn logging of connections on
0795: *
0796: * @param localUtil LocalizedResource to use to translate messages
0797: * @param request HttpServetRequest for forms
0798: * @param returnMessage localized continue message for continue button on error form
0799: * @return true if succeeded; false; otherwise
0800: */
0801: private boolean logging(LocalizedResource localUtil, boolean val,
0802: HttpServletRequest request, String returnMessage) {
0803: boolean retval = false;
0804: try {
0805: server.logConnections(val);
0806: retval = true;
0807: } catch (Exception e) {
0808: printErrorForm(localUtil, request, e, returnMessage);
0809: }
0810: return retval;
0811: }
0812:
0813: /**
0814: * Change tracing for all sessions
0815: *
0816: * @param localUtil LocalizedResource to use to translate messages
0817: * @param val if true, turn tracing on, if false turn it off
0818: * @param request HttpServetRequest for forms
0819: * @param returnMessage localized continue message for continue button on error form
0820: * @return true if succeeded; false; otherwise
0821: */
0822: private boolean traceAll(LocalizedResource localUtil, boolean val,
0823: HttpServletRequest request, String returnMessage) {
0824: boolean retval = false;
0825: try {
0826: server.trace(val);
0827: retval = true;
0828: } catch (Exception e) {
0829: printErrorForm(localUtil, request, e, returnMessage);
0830: }
0831: return retval;
0832: }
0833:
0834: /**
0835: * Change tracing for a given session
0836: *
0837: * @param localUtil LocalizedResource to use to translate messages
0838: * @param val if true, turn tracing on, if false turn it off
0839: * @param session session to trace
0840: * @param request HttpServetRequest for forms
0841: * @param returnMessage localized continue message for continue button on error form
0842: * @return true if succeeded; false; otherwise
0843: */
0844: private boolean traceSession(LocalizedResource localUtil,
0845: boolean val, int session, HttpServletRequest request,
0846: String returnMessage) {
0847: boolean retval = false;
0848: try {
0849: server.trace(session, val);
0850: retval = true;
0851: } catch (Exception e) {
0852: printErrorForm(localUtil, request, e, returnMessage);
0853: }
0854: return retval;
0855: }
0856:
0857: /**
0858: * Set trace directory
0859: *
0860: * @param localUtil LocalizedResource to use to translate messages
0861: * @param traceDirectory directory for trace files
0862: * @param request HttpServetRequest for forms
0863: * @param returnMessage localized continue message for continue
0864: * button on error form
0865: * @return true if succeeded; false; otherwise
0866: */
0867: private boolean traceDirectory(LocalizedResource localUtil,
0868: String traceDirectory, HttpServletRequest request,
0869: String returnMessage) {
0870: boolean retval = false;
0871:
0872: if ((traceDirectory == null) || traceDirectory.equals("")) {
0873: printErrorForm(localUtil, request, localUtil
0874: .getTextMessage("SRV_MissingParam", localUtil
0875: .getTextMessage("SRV_TraceDir")),
0876: returnMessage);
0877:
0878: return retval;
0879: }
0880:
0881: try {
0882: this .tracingDirectory = traceDirectory;
0883: server.setTraceDirectory(traceDirectory);
0884: retval = true;
0885: } catch (Exception e) {
0886: printErrorForm(localUtil, request, e, returnMessage);
0887: }
0888: return retval;
0889: }
0890:
0891: /**
0892: * Set Network server parameters
0893: *
0894: * @param localUtil LocalizedResource to use to translate messages
0895: * @param max maximum number of threads
0896: * @param slice time slice for each connection
0897: * @param request HttpServetRequest for forms
0898: * @param returnMessage localized continue message for continue
0899: * button on error form
0900: * @return true if succeeded; false; otherwise
0901: */
0902: private boolean setNetParam(LocalizedResource localUtil, int max,
0903: int slice, HttpServletRequest request, String returnMessage) {
0904: boolean retval = false;
0905:
0906: try {
0907: server.setMaxThreads(max);
0908: server.setTimeSlice(slice);
0909: retval = true;
0910: } catch (Exception e) {
0911: printErrorForm(localUtil, request, e, returnMessage);
0912: }
0913: return retval;
0914: }
0915:
0916: /**
0917: * Set defaults for logging and tracing (both off)
0918: */
0919: private void setDefaults() {
0920: logStatus = false;
0921: traceStatus = false;
0922: }
0923:
0924: /**
0925: * Get an integer parameter
0926: *
0927: * @param request HttpServetRequest for forms
0928: * @param name parameter name
0929: * @param fieldKey Key for the name of the field we're reading.
0930: * @param localUtil LocalizedResource to use in localizing messages
0931: * @param returnMessage localized continue message for continue
0932: * button on error form
0933: */
0934: private int getIntParameter(HttpServletRequest request,
0935: String name, String fieldKey, LocalizedResource localUtil,
0936: String returnMessage) {
0937: String val = request.getParameter(name);
0938: int retval;
0939: if (val == null || val.equals(""))
0940: return NOT_GIVEN;
0941: try {
0942: retval = (new Integer(val)).intValue();
0943: } catch (Exception e) {
0944: printErrorForm(localUtil, request, localUtil
0945: .getTextMessage("SRV_InvalidVal", val, localUtil
0946: .getTextMessage(fieldKey)), returnMessage);
0947: return INVALID;
0948: }
0949: if (retval < 0) {
0950: // negative integers not allowed for the parameters we're getting.
0951: printErrorForm(localUtil, request, localUtil
0952: .getTextMessage("SRV_InvalidVal", val, localUtil
0953: .getTextMessage(fieldKey)), returnMessage);
0954: return INVALID;
0955: }
0956: return retval;
0957: }
0958:
0959: /**
0960: * Print Derby Network Server banner
0961: */
0962: private void printBanner(LocalizedResource localUtil) {
0963: out.println("<a href=\"#navskip\">[ "
0964: + localUtil.getTextMessage("SRV_SkipToContent")
0965: + " ]</a>");
0966: out
0967: .println(" - <a href=\"" + SERVLET_ADDRESS + "\">[ "
0968: + localUtil.getTextMessage("SRV_BackToMain")
0969: + " ]</a>");
0970: out.println("<html>");
0971: out.println("<title>" + localUtil.getTextMessage("SRV_Banner")
0972: + "</title>");
0973: out.println("<body>");
0974: out.println("<hr>");
0975: out.println("<h1>" + localUtil.getTextMessage("SRV_Banner")
0976: + "</h1>");
0977: out.println("<hr>");
0978:
0979: }
0980:
0981: /**
0982: * Determine the locale file needed for this browsers preferences
0983: * Defaults to the settings for derby.locale and derby.codeset if set
0984: * English otherwise if browsers preferences can't be found
0985: *
0986: * @param request HttpServetRequest for forms
0987: * @return the appUI which fits the browsers preferences
0988: */
0989: private LocalizedResource getCurrentAppUI(HttpServletRequest request) {
0990: LocalizedResource localUtil;
0991: String acceptLanguage = request.getHeader("Accept-Language");
0992: localUtil = new LocalizedResource(null, null,
0993: SERVLET_PROP_MESSAGES);
0994: // if no language specified use one set by derby.locale, derby.codeset
0995: locale = null;
0996: if (acceptLanguage == null) {
0997: return localUtil;
0998: }
0999: // Use a tokenizer ot separate acceptable languages
1000: StringTokenizer tokenizer = new StringTokenizer(acceptLanguage,
1001: ",");
1002: while (tokenizer.hasMoreTokens()) {
1003: //Get the next acceptable language
1004: String lang = tokenizer.nextToken();
1005: lang = getLocStringFromLanguage(lang);
1006: int langindex = translationAvailable(lang);
1007: // have we found one
1008: if (langindex != -1) {
1009: localUtil.init(null, lang, SERVLET_PROP_MESSAGES);
1010: // locale will be passed to server, server routines will get set appropriately
1011: locale = lang;
1012: return localUtil;
1013: }
1014: }
1015: // nothing worked use defaults
1016: return localUtil;
1017:
1018: }
1019:
1020: /**
1021: * Get locale string from language which may have qvalue set
1022: *
1023: * @param lang language string to parse
1024: *
1025: * @return stripped language string to use in matching
1026: */
1027: private String getLocStringFromLanguage(String lang) {
1028: int semi;
1029: // Cut off any q-value that might come after a semi-colon
1030: if ((semi = lang.indexOf(';')) != -1) {
1031: lang = lang.substring(0, semi);
1032: }
1033: // trim any whitespace and fix the code, as some browsers might send a bad format
1034: lang = fixLanguageCode(lang.trim());
1035: return lang;
1036: }
1037:
1038: /**
1039: * Check if the required translation is available
1040: *
1041: * @param lang language we are looking for
1042: *
1043: * @return index into language array if found, -1 otherwise;
1044: */
1045: private int translationAvailable(String lang) {
1046: // assert lang == fixLanguageCode(lang)
1047: // we don't need to use toUpperCase() anymore, as the lang is already fixed
1048: for (int i = 0; i < knownLang.length; i++)
1049: if (knownLang[i].equals(lang))
1050: return i;
1051: return -1;
1052: }
1053:
1054: /**
1055: * Fix the language code, as some browsers send then in a bad format (for instance,
1056: * Firefox sends en-us instead of en_US).
1057: *
1058: * @param lang language to be fixed
1059: *
1060: * @return fixed version of the language, with _ separating parts and country in upper case
1061: */
1062: private String fixLanguageCode(String lang) {
1063: int index = lang.indexOf('-');
1064: if (index != -1) {
1065: return fixLanguageCode(lang, index);
1066: }
1067: index = lang.indexOf('_');
1068: if (index != -1) {
1069: return fixLanguageCode(lang, index);
1070: }
1071: return lang;
1072: }
1073:
1074: private String fixLanguageCode(String lang, int index) {
1075: return lang.substring(0, index) + "_"
1076: + lang.substring(index + 1).toUpperCase(Locale.ENGLISH);
1077: }
1078:
1079: /**
1080: * get an HTML labelled message from the resource bundle file, according to
1081: * the given key.
1082: */
1083: public String getHtmlLabelledMessageInstance(
1084: LocalizedResource localUtil, String key, String id) {
1085:
1086: if (id == null)
1087: id = "";
1088:
1089: return ("<label for='" + id + "'>"
1090: + localUtil.getTextMessage(key) + "</label>");
1091:
1092: }
1093:
1094: /**
1095: * Print the received string as a header.
1096: * @param str The string to be printed as a header.
1097: */
1098: private void printAsContentHeader(String str) {
1099:
1100: out.println("<a name=\"navskip\"></a><h2>" + str + "</h2>");
1101: return;
1102:
1103: }
1104:
1105: /**
1106: * If the received string has one or more single quotes
1107: * in it, replace each one with the HTML escape-code
1108: * for a single quote (apostrophe) so that the string
1109: * can be properly displayed on a submit button.
1110: * @param str The string in which we want to escape
1111: * single quotes.
1112: */
1113: private String escapeSingleQuotes(String str) {
1114:
1115: if ((str == null) || (str.indexOf("'") < 0))
1116: return str;
1117:
1118: char[] cA = str.toCharArray();
1119:
1120: // Worst (and extremely unlikely) case is every
1121: // character is a single quote, which means the
1122: // escaped string would need to be 4 times as long.
1123: char[] result = new char[4 * cA.length];
1124:
1125: int j = 0;
1126: for (int i = 0; i < cA.length; i++) {
1127:
1128: if (cA[i] == '\'') {
1129: result[j++] = '&';
1130: result[j++] = '#';
1131: result[j++] = '3';
1132: result[j++] = '9';
1133: } else
1134: result[j++] = cA[i];
1135:
1136: }
1137:
1138: return new String(result, 0, j);
1139:
1140: }
1141:
1142: private static boolean isServerStarted(NetworkServerControl server,
1143: int ntries) {
1144: for (int i = 1; i <= ntries; i++) {
1145: try {
1146: Thread.sleep(500);
1147: server.ping();
1148: return true;
1149: } catch (Exception e) {
1150: if (i == ntries)
1151: return false;
1152: }
1153: }
1154: return false;
1155: }
1156:
1157: }
|