I’m working in a project based on Flex and Apache Mina. I’m using FlexBuilder 3 for the development of the client side and for debugging. Everything works great in debug mode but as soon as I deploy the application in IIS or Tomcat I started getting the sandbox security violation. This error indicates that the Flex application was unable to find the cross domain XML to allow the connection to the domain where the Mina socket server is running. I googled about this problem and I found out that this problem is very common and people are having a hard time finding a solution. I also spent some time working on the problem and I was succesful in finding a solution. Below is my solution.

First, the latest version of the Flash player implicitly looks for the cross domain XML in port 843 of the domain where the Flex application is deployed.  You can also explicitly tell the Flash player where to read this XML by adding:

Security.loadPolicyFile(“http://domainIP:843”);

This is my policy server listening to port 843:

package flexmina2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class PolicyServer extends IoHandlerAdapter
{
protected String _policy;
protected static final int MASTER_PORT = 843;

public static IoAcceptor init (
int socketPolicyPort, String serverHost, int[] ports)
throws IOException
{
IoBuffer buffer = IoBuffer.allocate(256, true);
buffer.setAutoExpand(true);
IoAcceptor acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast(“codec”, new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName(“UTF-8”))));
new PolicyServer(socketPolicyPort, serverHost, ports), cfg);

acceptor.setHandler(new PolicyServer(socketPolicyPort, serverHost, serverPorts);
acceptor.bind(new InetSocketAddress(socketPolicyPort));
return acceptor;
}

/** Create a new server instance. */
public PolicyServer (
int policyPort, String serverHost, int[] serverPorts)
{
StringBuilder policyBuilder = new StringBuilder().
append(“\n”).
append(“\n”);
if (policyPort== MASTER_PORT) {
policyBuilder.append(
” \n”);
}

for (String host : new String[] { serverHost }) {
policyBuilder.append(” \n”);
}
policyBuilder.append(“\n”);

_policy = policyBuilder.toString();
}

@Override
public void messageReceived (IoSession session, Object msg) {
}

@Override
public void sessionIdle (IoSession session, IdleStatus status)
throws Exception
{
session.close();
}

@Override
public void sessionCreated (IoSession session)
throws Exception
{
session.write(_policy);
session.write(“\u0000”); — > send a null byte
}

@Override
public void exceptionCaught (IoSession session, Throwable cause)
{
System.out.println(cause);
}

}// end of class

The policy server listens to request on port 843 and replies with the cross domain XML. Inside the sessionCreated function it is very important that a null byte is sent right after the policy is sent. If you don’t send a null byte, the Flex application will ignore the policy and complaint with the security sandbox violation.

A very useful way to debug policy security violations is by enabling the logging of Flah player policy errors. This can be done by appending the following to the end of the file mm.cfg (do a file search in your computer to find the location of this file):

ErrorReportingEnable=1
TraceOutputFileEnable=1
PolicyFileLog=1

Any problems related to the policy will be log in the policyFiles.txt (do a file search in your computer to find the location of this file).

*Update*: When deploying your application in a slow network (latency > 3 seconds) the Flex application will try to read the policy XML but it will fail with the security error due to the 3 seconds timeout. To avoid this problem it is a better design to explicitly call to load the policy like follows:

Security.LoadPolicyFile(“xmlsocket://domainIP:843”);
sockect.connect(hots, port);

The Flash player will wait all the time that it needs to wait to get the policy and then open the socket connection. These hints will save you hours of frustrations.

I hope you find this article helpful,

Alberto Acevedo



I’m working in a project dealing with a Flex client mapping application that uses remoting to communicate to a Tomcat 6.0.26  server using  Blazeds + Spring 3.0.1 + iBatis + ActiveMQ 5.3.1, and jDK 1.6.0_20 . This application has the characteristic of producing a high amount of short live objects (roads, bridges, symbols) and a few long live objects. If I run Tomcat with the default JVM configurations and set the  JvmMs, JvmMx large enough depending on my available RAM and type of server (I use a 32 bits windows 2003 server, 3.25GB RAM, and with 2 CPUs that allows a max JvmMx of approximately 1256m) , the PS old gen space overflows after a few hours of execution and I was getting the out of memory (OOM)  error. The default GC could not keep up with the high amount of short live objects and it was overflowing the survivor space resulting in the allocation of the short live objects into the old perm space.  When this happens the GC fails to collect the objects from the old perm space and it is just a matter of time for the server to reach the out of memory error. I first thought it was a memory leak but after using  the Netbeans Profiler I didn’t see any leaks in my code. I tried different JVM configurations and I kept getting the OOM.  Finally I nailed the right configuration by using the following JVM configuration:

-XX:+UseConcMarkSweepGC
-XX:+UseParNewGC
-XX:+CMSClassUnloadingEnabled
-XX:+CMSParallelRemarkEnabled
-XX:CMSInitiatingOccupancyFraction=30
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
-XX:ParallelCMSThreads=2
-XX:+UseCMSCompactAtFullCollection
-XX:+DisableExplicitGC
-XX:MaxHeapFreeRatio=70
-XX:MinHeapFreeRatio=40
-XX:MaxTenuringThreshold=30
-XX:NewSize=450m
-XX:MaxNewSize=450m
-XX:SurvivorRatio=2
-XX:PermSize=150m
-Dcom.sun.management.jmxremote

–JvmMs 1024 –JvmMx 1024 –JvmSs 256

Pay attention to the MaxTenuringThreshold. I set  the MaxTenuringThreshold to a high value to give the GC enough chances  to collect the short live objects  while they are at the eden and survivor spaces. The result is an old perm space that is almost empty and most of the GC collecting happening in the eden and survivor spaces. The performance of the application is very high and my customers are very happy!

Update (June 18, 2010) – Added UseCMSCompactAtFullCollection and CMSInitiatingOccupancyFraction to avoid page fragmentation. Before adding these parameters my tenure space was filling up slowly  when the Tomcat server was under heavy load.  heavy load in my case was when the eden space was filling up the 225m allocated space every 25 seconds and the GC was collecting most of the objects,  but some of the short live objects ended up in the tenure space. Those short live objects in the tenure glued to the space and the GC failed to collect them indicating to me a problem with fragmentation. After adding the 2 JVM parameters the tenure space is always empty or near empty indicating that all the short live objects are correctly ( as expected based on my JVM parameters) collected at the eden or survivor spaces (also known as the new spaces) . Now that the tenure space is seldom used I could increase the -XX:NewSize and the -XX:MaxNewSize to increment the size of the eden and survivor spaces and reduce the size of the tenure space.  This change would reduce the number of collecting at the new spaces and improve performance.

The open source  PSI-Prove monitoring tool for Tomcat is a great tool that helped me a lot while I was tuning the JVM setting for my Tomcat server.  To try this tool go to http://code.google.com/p/psi-probe/.

Tuning the JVM is never an easy task ( tuning dependent on hardware resources and web application characteristics) and having a GC with poor performance can badly affect the performance of a well implemented web application. I hope you find this article useful.

Alberto Acevedo