<init-param>
   <nazwa_parametru>development</param-name>
   <param-value>false</param-value>
</init-param>
<init-param>
   <param-name>genStrAsCharArray</param-name>
   <param-value>true</param-value>
</init-param>
--------------------------------------------------------------------------------------------------------------------------------------
public void processRequest (HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
      ...
      request.getRequestDispatcher(url).forward (request, respsonse);
}

public void processRequest (HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
      ...
      response.sendRedirect(url);
}
--------------------------------------------------------------------------------------------------------------------------------------
<servlet>
   <servlet-name>ElTesterJsp</servlet-name>
   <jsp-file>/elTester.jsp</jsp-file>
</servlet>
<servlet-mapping>
   <servlet-name>ElTesterJsp</servlet-name>
   <url-pattern>/elTester.jsp</url-pattern>
</servlet-mapping>
--------------------------------------------------------------------------------------------------------------------------------------
/**
 * Opisuje dane, ktre bd udostpniane przez JMX.
 */
public interface StatsMBean {
      /**
       * @return Liczba da
       */
      public int getCount();

      /**
       * @return Nazwa obiektu stat
       */
      public String getName();

      /**
       * @return Opis obiektu stat
       */
      public String getDescription();

      /**
       * @return redni czas odpowiedzi w milisekundach
       */
      public double getMean();

      /**
      * @return Odchylenie standardowe czasu odpowiedzi w milisekundach
      */
      public double getStandardDeviation();

      /**
       * @return Minimalny czas odpowiedzi w milisekundach
       */
      public double getMin();

      /**
       * @return Maksymalny czas odpowiedzi w milisekundach
       */
      public double getMax();
      /**
       * @return Mediana czasu odpowiedzi w milisekundach
       */
      public double getTP50();
      /**
       * @return Percentyl 90% czasu odpowiedzi w milisekundach
       */
      public double getTP90();
      /**
       * @return Percentyl 99% czasu odpowiedzi w milisekundach
       */
      public double getTP99();

      /**
       * Wyczyszczenie danych prbki
       */
      public void reset();
}
--------------------------------------------------------------------------------------------------------------------------------------
public class Stats implements StatsMBean {
      private static final int DEFAULT_ITEM_COUNT = 1000;
      private String description;
      private String name;
      private AtomicInteger count;

      private DescriptiveStatistics stats;

      public Stats(String name, String description) {
            this (name, description, DEFAULT_ITEM_COUNT);
      }

      public Stats(String name, String description, int sampleCount) {
            this.name = name;
            this.description = description;
            stats = new SynchronizedDescriptiveStatistics(sampleCount);
            count = new AtomicInteger();
      }

      public void addValue (double v) {
            stats.addValue(v);
            count.incrementAndGet();
      }
      public int getCount() {
            return count.get();
      }

      public double getMin() {
            return stats.getMin();
      }

      public double getMax() {
            return stats.getMax();
      }

      public double getTP50() {
            return stats.getPercentile(50.0);
      }

      public double getTP90() {
            return stats.getPercentile(90.0);
      }

      public double getTP99() {
            return stats.getPercentile(99.0);
      }

      public double getStandardDeviation() {
            return stats.getStandardDeviation();
      }

      public String getName() {
            return name;
      }

      public String getDescription() {
            return description;
      }

      public double getMean() {
            return stats.getMean();
      }

      // Reset obiektu stats
      public void reset() {
            stats.clear();
            count.set(0);
      }
}
--------------------------------------------------------------------------------------------------------------------------------------
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContext;

public class ControlServletContextListener
    implements ServletContextListener {
      public void contextInitialized(
          ServletContextEvent servletContextEvent) {
        // Rejestracja MBeana dla tego serwletu
        ServletContext context =
            servletContextEvent.getServletContext();
        String path = context.getContextPath();
        StatsMBean statsMBean = new Stats(path, "ServletRequest stats");
        String statName =
            "javaperfbook.web.sample:name=ServletRequest ("+path+" )";
        StatsExporter.getInstance().export(statName, statsMBean);
        context.setAttribute("statsMBean", statsMBean);
    }

    public void contextDestroyed(
        ServletContextEvent servletContextEvent) {
        StatsExporter.getInstance().unExportAll();
    }
}

import javax.management.*;
import java.lang.management.ManagementFactory;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.logging.Logger;

public class StatsExporter {
    private static StatsExporter instance = new StatsExporter();
    private Set<ObjectName> exportBeans = new HashSet<ObjectName>();
    private static Logger logger =
        Logger.getLogger(StatsExporter.class.getName());

    public static StatsExporter getInstance() {
        return instance;
    }

    public void export (String name, StatsMBean bean) {
        try {
            ObjectName oName = new ObjectName(name);
ManagementFactory.getPlatformMBeanServer()
                             .registerMBean(bean, oName);
            exportBeans.add(oName);
        } catch (MalformedObjectNameException e) {
            handleException(e);
        } catch (NotCompliantMBeanException e) {
            handleException(e);
        } catch (MBeanRegistrationException e) {
            handleException(e);
        } catch (InstanceAlreadyExistsException e) {
            handleException(e);
        }
    }

    private void unexport (ObjectName oName) {
        try {
            ManagementFactory.getPlatformMBeanServer()
                             .unregisterMBean(oName);
        } catch (MBeanRegistrationException e) {
            handleException(e);
        } catch (InstanceNotFoundException e) {
            handleException(e);
        }
    }

    public void unExportAll() {
        Iterator<ObjectName> iter = exportBeans.iterator();
        while (iter.hasNext()) {
            unexport(iter.next());
        }
        exportBeans.clear();
    }

    private void handleException (Exception e) {
        logger.warning(e.getMessage());
        e.printStackTrace();
    }
}
--------------------------------------------------------------------------------------------------------------------------------------
<web-app xmlns="http://java.sun.com/xml/ns/javaee"...
    ...
    <listener>
        <display-name>ContextListener</display-name>
        <listener-class>
           javaperfbook.web.sample.ControlServletContextListener
        </listener-class>
    </listener>
</web-app>
--------------------------------------------------------------------------------------------------------------------------------------
import javax.servlet.*;
import java.io.IOException;

public class StatsFilter implements Filter {
    private FilterConfig config;
    public void doFilter(ServletRequest req,
                         ServletResponse resp,
                         FilterChain chain)
        throws ServletException, IOException {
        long start = System.nanoTime();
        chain.doFilter(req, resp);
        double elapsed = (System.nanoTime()-start)/1e6;
        Stats stat = (Stats) config.getServletContext().
                                    getAttribute("statsMBean");
        if (stat ! = null) {
            stat.addValue(elapsed);
        }
    }

    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    public void destroy() {
    }
}
--------------------------------------------------------------------------------------------------------------------------------------
public class SampleServlet extends HttpServlet {
      public void init() {
            ....
      }
      ...
}
--------------------------------------------------------------------------------------------------------------------------------------
<webapp ..>
   ..
   <listener>
      <display-name>ContextListener</display-name>
      <listener-class>
         javaperfbook.web.sample.ControlServletContextListener
      </listener-class>
   </listener>
</webapp>
--------------------------------------------------------------------------------------------------------------------------------------
            <web-app ...>
            <jsp-config>
             <jsp_property-group>
              <url-pattern>
               *.jsp
              </url-pattern>
              <trim-directive-whitespaces>
               true
              </trim-directive-whitespaces>
             </jsp_property-group>
            </jsp-config>
            <web-app>
--------------------------------------------------------------------------------------------------------------------------------------
<init-param>
      <param-name>trimSpaces</param-name>
      <param-value>true</param-value>
</init-param>
--------------------------------------------------------------------------------------------------------------------------------------
<jsp:useBean beanName="perfbook.SimpleBean" type="perfbook.SimpleBean"
id="sbean" scope="page"/>
<html>
   <body>
bean value = ${sbean.value}
   </body>
</html>
--------------------------------------------------------------------------------------------------------------------------------------
<tbody>
     <% List<Shape> list = sc.getRandomShapes();
     for (Shape shape: list) {
     %>
      <tr style="background-color: <% = shape.getColor() %>">
            <td><%= shape.getType() %></td>
               <td><%= shape.getAreaStr() %></td>
               <td><%= shape.getPerimeterStr() %></td>
          </tr>
      <% } %>
</tbody>
--------------------------------------------------------------------------------------------------------------------------------------
public class SimpleDataContainer implements Serializable {
    private String name;
    private long lastUpdatedTime;
    private List<SimpleData> dataList;
    private Date createdDate;
...	

public class SimpleData implements Serializable {
    private long id;
    private long createdTime;
    private long lastUpdatedTime;
    private String author;
    private String description;
...

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.codehaus.jackson.type.JavaType;

import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;

public class JsonDataSerializer<T> implements DataSerializer<T> {
    private static ObjectMapper mapper = new ObjectMapper();
    JavaType type;

    public JsonDataSerializer(Class<T> type) {
        this.type = TypeFactory.type(type);
    }

    public byte[] serialize(T object) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        mapper.writeValue(bos, object);

        return bos.toByteArray();
    }

    public T deSerialize(byte[] buf) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(buf);
        T obj = (T) mapper.readValue(bis, type);
        return obj;
    }

    public SerializationMode getSerializationMode() {
        return SerializationMode.JSON_SERIALIZATION;
    }
}

import com.ning.compress.lzf.LZFOutputStream;
import com.ning.compress.lzf.LZFInputStream;

import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;

public class LZFCompressor extends Compressor {
    public byte[] compress(byte[] buf) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        LZFOutputStream os = new LZFOutputStream(bos);
        os.write(buf);
        os.close();
        return bos.toByteArray();
    }

    public byte[] uncompress(byte[] buf) throws IOException {
        LZFInputStream is = new LZFInputStream(new
ByteArrayInputStream(buf));
        byte[] data = new byte[8192];
        int count;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((count=is.read(data)) != -1) {
            bos.write(data, 0, count);
        }
        is.close();
        return bos.toByteArray();
    }

    public CompressionMode getCompressionMode() {
        return CompressionMode.LZF;
    }
}
--------------------------------------------------------------------------------------------------------------------------------------
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TraceFilter implements Filter {
    public void doFilter(ServletRequest req,
                         ServletResponse resp,
                         FilterChain chain)
        throws ServletException, IOException {
        // Ustawianie ladu, jeli dotd go nie byo.
        TraceManager traceManager = null;
        if (req instanceof HttpServletRequest &&
            resp instanceof HttpServletResponse) {
            HttpServletRequest hreq = (HttpServletRequest) req;
            HttpServletResponse hres = (HttpServletResponse) resp;
            traceManager = new TraceManager();
            traceManager.setTrace(hreq, hres);
        }

        chain.doFilter(req, resp);
        if (traceManager ! = null)
            traceManager.removeTrace();
    }
...
}
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class TraceManager {
    private static ThreadLocal<String> traceTLS = new ThreadLocal<String>();
    public static final String TRACE_HEADER = "TRACE";

    public String getTrace() {
        String trace = traceTLS.get();
        if (trace = = null)
            trace = UUID.randomUUID().toString();
        return trace;
    }

    public void setTrace (HttpServletRequest req,
                          HttpServletResponse res) {
        String trace = req.getHeader(TRACE_HEADER);
        if (trace = = null) {
            trace = UUID.randomUUID().toString();
            req.setAttribute(TRACE_HEADER, trace);
        }
        res.setHeader(TRACE_HEADER, trace);
        traceTLS.set(trace);
        logger.fine("lad ustawiony dla " + trace);
    }

    public void removeTrace() {
        traceTLS.remove();
    }
}


