Creating a label with SWT

Main.java:

import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.*;
 
public class Main {
   public static void main(String[] args) {
      Display display = new Display();
      Shell shell = new Shell(display);

      // pos x, pos y, width, height
      shell.setBounds(200, 200, 300, 200);
      shell.setText("Label Demonstration");
      shell.setLayout(new GridLayout());

      Label label = new Label(shell, SWT.CENTER);
      label.setText("This is a label");

      shell.open();

      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
      display.dispose();
   }
}

Creating a menu with SWT

Main.java:

import org.eclipse.swt.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
 
public class Main
{
   public static void main(String[] args) {
      Display display = new Display();
      final Shell shell = new Shell(display);
      shell.setText("SWT MenuBar Demonstration");
  
      Menu menuBar = new Menu(shell, SWT.BAR);
  
      Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
      MenuItem fileItem = new MenuItem(menuBar, SWT.CASCADE);
 
      // try switching next two lines, and see what happens!
      fileItem.setText("File");
      fileItem.setMenu(fileMenu);
 
      MenuItem openItem = new MenuItem(fileMenu, SWT.NULL);
      openItem.setText("Open");
      openItem.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(SelectionEvent event) {
         	System.out.println("Open selected!");
         }
      });
  
      MenuItem exitItem = new MenuItem(fileMenu, SWT.NULL);
      exitItem.setText("Exit");
      exitItem.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(SelectionEvent event) {
            shell.close();
         }
      });
       
      shell.setSize(200, 200);
      shell.setMenuBar(menuBar);
      shell.open();
       
      while (!shell.isDisposed()) {
         if (!display.readAndDispatch()) {
            display.sleep();
         }
      }
   }
}

Writing your own Tomcat Valve

You can extend from org.apache.catalina.valves.ValveBase and implement the method invoke. The following example just prints out is has been called and invokes the next Valve.

MyValve.java:

import javax.servlet.http.*;
import javax.servlet.*;
import java.util.*;
import java.io.*;
import org.apache.catalina.valves.*;
import org.apache.catalina.*;
 
public class MyValve extends ValveBase
{
   /**
    * The descriptive information related to this implementation.
    */
   private static final String info = "MyValve/1.0";
 
   /**
    * Return descriptive information about this Valve implementation.
    */
   public String getInfo() {
      return (info);
   }
 
   public void invoke(Request request, Response response, ValveContext context)
                             throws IOException, ServletException {
      // Skip logging for non-HTTP requests and responses
      if (!(request instanceof HttpRequest) ||
          !(response instanceof HttpResponse)) {
         context.invokeNext(request, response);
         return;
      }
 
      HttpRequest httpRequest   = (HttpRequest) request;
      HttpResponse httpResponse = (HttpResponse) response;
      HttpServletRequest httpServletRequest   = (HttpServletRequest) httpRequest.getRequest();
      HttpServletResponse httpServletResponse = (HttpServletResponse) httpResponse.getResponse();
 
      System.out.println("nnnMyValve invokednnn");
 
      // continue processing the request
      context.invokeNext(request, response);
   }
 
   public String toString() {
      StringBuffer sb = new StringBuffer();
      sb.append("MyValve[");
      if (container != null) {
         sb.append(container);
      }
      sb.append("]");
      return sb.toString();
   }
}

Compile it with catalina.jar and servlet.jar in your classpath and place it in /server/classes.

Denying/allowing access to certain hosts in Tomcat

Use the Remote Host Filter Valve. [A valve, Tomcat only, is a Java class that preprocesses access requests. You can associate valves in server.xml to the containers engine, host and context.] It allows you to specify, at configuration time, whether or not requests coming from certain (sets of) hosts should be allowed or denied (using regular expressions). By default, all accesses are allowed. Look in server.xml for RemoteHostValve.

eg.

   <Valve className="org.apache.catalina.valves.RemoteHostValve" deny="esuswin*"/>

Will deny access to my computer named esuswin2000.

Denying/allowing access to certain IP addresses in Tomcat

Use the Remote Address Filter Valve. [A valve, Tomcat only, is a Java class that preprocesses access requests. You can associate valves in server.xml to the containers engine, host and context.] It allows you to specify, at configuration time, whether or not requests coming from certain (sets of) IP addresses should be allowed or denied (using regular expressions). By default, all accesses are allowed. Look in server.xml for RemoteAddrValve.

eg.

   <Valve className="org.apache.catalina.valves.RemoteAddrValve" deny="127.0.0.*"/>

Specify the kind of information written in the tomcat access log files

Log files are written by the Tomcat valve AccessLogValve. A valve, Tomcat only, is a Java class that preprocesses access requests. You can associate valves in server.xml to the containers engine, host and context.

Possible attributes for the AccessLogValve are the following.

  • directory: the directory to where the log files are written, can be relative to CATALINA_HOME or absolute, default value: logs

  • pattern: specifies what type of infomration a log line should contain. You can combine any of the following patterns:
    %a - Remote IP address 
    %A - Local IP address 
    %b - Bytes sent, excluding HTTP headers, or '-' if zero 
    %B - Bytes sent, excluding HTTP headers 
    %h - Remote host name (or IP address if resolveHosts is false) 
    %H - Request protocol 
    %l - Remote logical username from identd (always returns '-') 
    %m - Request method (GET, POST, etc.) 
    %p - Local port on which this request was received 
    %q - Query string (prepended with a '?' if it exists) 
    %r - First line of the request (method and request URI) 
    %s - HTTP status code of the response 
    %t - Date and time, in Common Log Format 
    %u - Remote user that was authenticated (if any), else '-' 
    %U - Requested URL path 
    %v - Local server name 
    

    Specifying common is the same as specifying %h %l %u %t “%r” %s %b.
    For example:
    With pattern common:

    127.0.0.1 - - [21/Jul/2002:20:16:31 -0800] "GET /index.html HTTP/1.1" 200 6827
    127.0.0.1 - - [21/Jul/2002:20:16:31 -0800] "GET /tomcat.gif HTTP/1.1" 200 1934
    127.0.0.1 - - [21/Jul/2002:20:16:31 -0800] "GET /jakarta-banner.gif HTTP/1.1" 304 -
    127.0.0.1 - - [21/Jul/2002:20:16:32 -0800] "GET /tomcat-power.gif HTTP/1.1" 304 -
    

    With pattern Request from %a: %r:

    Request from 127.0.0.1: GET /index.html HTTP/1.1
    Request from 127.0.0.1: GET /tomcat.gif HTTP/1.1
    Request from 127.0.0.1: GET /jakarta-banner.gif HTTP/1.1
    Request from 127.0.0.1: GET /tomcat-power.gif HTTP/1.1
    
  • prefix: a string that should be added to the start of each log filename, default value: access_log
  • suffix: a string that should be added to the end of each log filename, default value: empty
  • resolveHosts: a boolean value, if set to true, it will look up the corresponding host name for the requesting IP address. Use it only if absolutely necessary, it will slow down Tomcat a lot.
  • Changing the directory where the Tomcat access log files are written

    Log files are written by the Tomcat valve AccessLogValve. A valve, Tomcat only, is a Java class that preprocesses access requests. You can associate valves in server.xml to the containers engine, host and context.

    Search TOMCAT_HOME/conf/server.xml for “AccessLogValve”. Specify the attribute directory as shown in this example:

       <Valve className="org.apache.catalina.valves.AccessLogValve"
              directory="c:\tomcat\logs"  prefix="localhost_access_log." suffix=".txt"
              pattern="common"/>
    

    This will cause all the access logs of the hosting container to be written to c:\tomcat\logs.

    What is a Valve?

    A Valve is not defined in the Servlet/JSP spec, it is Tomcat specific. From the Tomcat docs:
    A Valve element represents a component that will be inserted into the request processing pipeline for the associated Catalina container (Engine, Host, or Context).

    For example, with the valve Remove Address Filter, you can decide whether or not to continue processing the request based on a regular expression that takes as input the IP address of the client.

    You associate a Valve with a particular container (Engine, Host, or Context) in server.xml.

    Check out the Q/A’s on how to use the Valves that come with Tomcat, and how to write your own.

    Running Tomcat with a security manager

    Create a web application that contains the following jsp:

    <html>
    <body>
    Trying to shutdown Tomcat, please press reload.
    <%
       System.exit(1);
    %>
    </body>
    </html>
    

    Run Catalina (eg. catalina run) and load up the jsp. Notice in the Tomcat console that Tomcat has exited. What happens is that, by default, Tomcat is started without a security manager. The JSP, that was compiled into a servlet, runs in the same Virtual Machine as Tomcat itself, and System.exit causes the currently running VM to exit.

    To prevent this from happening, run Tomcat with a Security Manager to not permit web applications to perform these kinds of operations. The security policy file used by Catalina is catalina.policy located in the [TOMCAT-HOME]/conf directory.

    If you start Catalina again with the option -security (eg. catalina run -security, or startup -security), catalina.policy is taken into account.

    If you then load the jsp, you would get the following error message in your browser window:

    java.security.AccessControlException: access denied (java.lang.RuntimePermission exitVM)
    	at java.security.AccessControlContext.checkPermission(AccessControlContext.java:272)
    	at java.security.AccessController.checkPermission(AccessController.java:399)
    	at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
    	at java.lang.SecurityManager.checkExit(SecurityManager.java:765)
    	at java.lang.Runtime.exit(Runtime.java:91)
    	at java.lang.System.exit(System.java:701)
    	at org.apache.jsp.ExitTomcat$jsp._jspService(ExitTomcat$jsp.java:59)
    	at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    . . .