[hornetq-commits] JBoss hornetq SVN: r7918 - in trunk: examples/common and 8 other directories.

do-not-reply at jboss.org do-not-reply at jboss.org
Wed Aug 26 10:21:01 EDT 2009


Author: jmesnil
Date: 2009-08-26 10:21:01 -0400 (Wed, 26 Aug 2009)
New Revision: 7918

Added:
   trunk/examples/jms/applet/
   trunk/examples/jms/applet/applet.html
   trunk/examples/jms/applet/build.xml
   trunk/examples/jms/applet/readme.html
   trunk/examples/jms/applet/server0/
   trunk/examples/jms/applet/server0/hornetq-beans.xml
   trunk/examples/jms/applet/server0/hornetq-configuration.xml
   trunk/examples/jms/applet/server0/hornetq-jms.xml
   trunk/examples/jms/applet/server0/hornetq-users.xml
   trunk/examples/jms/applet/src/
   trunk/examples/jms/applet/src/org/
   trunk/examples/jms/applet/src/org/hornetq/
   trunk/examples/jms/applet/src/org/hornetq/jms/
   trunk/examples/jms/applet/src/org/hornetq/jms/example/
   trunk/examples/jms/applet/src/org/hornetq/jms/example/AppletExample.java
   trunk/examples/jms/applet/src/org/hornetq/jms/example/HttpStaticFileServer.java
   trunk/examples/jms/applet/src/org/hornetq/jms/example/HttpStaticFileServerHandler.java
   trunk/examples/jms/applet/src/org/hornetq/jms/example/HttpStaticFileServerPipelineFactory.java
Modified:
   trunk/.classpath
   trunk/examples/common/build.xml
Log:
HORNETQ-113: Applet example

* added example to send/receive messages from an applet.
* example is manual and is not executed by "ant all" from common directory

Modified: trunk/.classpath
===================================================================
--- trunk/.classpath	2009-08-26 11:11:08 UTC (rev 7917)
+++ trunk/.classpath	2009-08-26 14:21:01 UTC (rev 7918)
@@ -17,6 +17,7 @@
 	<classpathentry kind="src" path="examples/core/microcontainer/src"/>
 	<classpathentry kind="src" path="examples/core/embedded-remote/src"/>
 	<classpathentry kind="src" path="examples/core/perf/src"/>
+	<classpathentry kind="src" path="examples/jms/applet/src"/>
 	<classpathentry kind="src" path="examples/jms/application-layer-failover/src"/>
 	<classpathentry kind="src" path="examples/jms/automatic-failover/src"/>
 	<classpathentry kind="src" path="examples/jms/bridge/src"/>

Modified: trunk/examples/common/build.xml
===================================================================
--- trunk/examples/common/build.xml	2009-08-26 11:11:08 UTC (rev 7917)
+++ trunk/examples/common/build.xml	2009-08-26 14:21:01 UTC (rev 7918)
@@ -187,9 +187,12 @@
             <include name="jms/*/build.xml"/>
             <exclude name="common/build.xml"/>
             <exclude name="core/perf/build.xml"/>
+            <exclude name="jms/applet/build.xml"/>
             <exclude name="jms/perf/build.xml"/>
          </fileset>
       </subant>
+   	
+   	  <echo message="Do not forget to run jms/applet example manually!" />
    </target>
 
 </project>


Property changes on: trunk/examples/jms/applet
___________________________________________________________________
Name: svn:ignore
   + build


Added: trunk/examples/jms/applet/applet.html
===================================================================
--- trunk/examples/jms/applet/applet.html	                        (rev 0)
+++ trunk/examples/jms/applet/applet.html	2009-08-26 14:21:01 UTC (rev 7918)
@@ -0,0 +1,17 @@
+<html>
+  <head>
+    <title>HornetQ Applet Example</title>
+  </head>
+  <body>
+     <h1>HornetQ Applet Example</h1>
+     
+     <p>The Applet will connect to HornetQ server running on localhost and
+     publishes messages on a topic <code>exampleTopic</code> when "Send" is pressed.</p>
+     <p>The Applet is also a MessageListener and will display messages received from the topic</p>
+     
+     <applet code="org.hornetq.jms.example.AppletExample.class"
+             codebase="build/classes/"
+             archive="hornetq-core-client.jar,hornetq-jms-client.jar,jboss-jms-api.jar,hornetq-transports.jar,netty.jar"
+             width="640" height="480"></applet>
+  </body>
+</html>
\ No newline at end of file

Added: trunk/examples/jms/applet/build.xml
===================================================================
--- trunk/examples/jms/applet/build.xml	                        (rev 0)
+++ trunk/examples/jms/applet/build.xml	2009-08-26 14:21:01 UTC (rev 7918)
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE project [
+      <!ENTITY libraries SYSTEM "../../../thirdparty/libraries.ent">
+      ]>
+<!--
+  ~ Copyright 2009 Red Hat, Inc.
+  ~ Red Hat licenses this file to you under the Apache License, version
+  ~ 2.0 (the "License"); you may not use this file except in compliance
+  ~ with the License.  You may obtain a copy of the License at
+  ~    http://www.apache.org/licenses/LICENSE-2.0
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+  ~ implied.  See the License for the specific language governing
+  ~ permissions and limitations under the License.
+  -->
+
+<project default="run" name="HornetQ Applet Example">
+
+   <import file="../../common/build.xml"/>
+
+   <path id="extra.classpath">
+      <fileset file="${jars.dir}/org/jboss/netty/lib/netty.jar" />
+   </path>
+
+   <path id="applet.classpath">
+      <fileset dir="build/classes" />
+	  <fileset dir="build/classes">
+	     <include name="**/*.jar"/>
+	  </fileset>
+   </path>
+	
+   <target name="init">
+      <mkdir dir="build/classes" />
+	  <copy todir="build/classes">
+	     <fileset dir="${hornetq.jars.dir}">
+	        <include name="hornetq-core-client.jar"/>
+	        <include name="hornetq-jms-client.jar"/>
+	        <include name="hornetq-transports.jar"/>
+	     </fileset>
+	     <fileset file="${jars.dir}/org/jboss/netty/lib/netty.jar" />
+	   	 <fileset file="${jars.dir}/org/jboss/javaee/lib/jboss-jms-api.jar" />
+	  </copy>
+   </target>
+
+   <target name="run" depends="init">
+      <antcall target="runExample">
+	     <param name="example.classname" value="org.hornetq.jms.example.HttpStaticFileServer"/>
+	  </antcall>
+   </target>
+</project>

Added: trunk/examples/jms/applet/readme.html
===================================================================
--- trunk/examples/jms/applet/readme.html	                        (rev 0)
+++ trunk/examples/jms/applet/readme.html	2009-08-26 14:21:01 UTC (rev 7918)
@@ -0,0 +1,20 @@
+<html>
+  <head>
+    <title>HornetQ Applet Example</title>
+    <link rel="stylesheet" type="text/css" href="../../common/common.css">
+  </head>
+  <body>
+     <h1>Applet Example</h1>
+     <br>
+     <p>This example shows you how to send and receive JMS messages from an Applet.</p>
+     
+	 <h2>Example step-by-step</h2>
+     
+     <p><i>To run the example, simply type <code>ant</code> from this directory</i> to start
+     HornetQ server and a HTTP server.</p>
+     
+     <p>Then, go to <a href="http://127.0.0.1:8088/applet.html">http://127.0.0.1:8088/applet.html</a> to load
+     and use the applet.</p>
+     
+  </body>
+</html>
\ No newline at end of file


Property changes on: trunk/examples/jms/applet/server0
___________________________________________________________________
Name: svn:ignore
   + data


Added: trunk/examples/jms/applet/server0/hornetq-beans.xml
===================================================================
--- trunk/examples/jms/applet/server0/hornetq-beans.xml	                        (rev 0)
+++ trunk/examples/jms/applet/server0/hornetq-beans.xml	2009-08-26 14:21:01 UTC (rev 7918)
@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<deployment xmlns="urn:jboss:bean-deployer:2.0">
+
+   <bean name="Naming" class="org.jnp.server.NamingBeanImpl"/>
+
+   <!-- JNDI server. Disable this if you don't want JNDI -->
+   <bean name="JNDIServer" class="org.jnp.server.Main">
+      <property name="namingInfo">
+         <inject bean="Naming"/>
+      </property>
+      <property name="port">1099</property>
+      <property name="bindAddress">localhost</property>
+      <property name="rmiPort">1098</property>
+      <property name="rmiBindAddress">localhost</property>
+   </bean>
+   
+   <!-- MBean server -->
+   <bean name="MBeanServer" class="javax.management.MBeanServer">
+      <constructor factoryClass="java.lang.management.ManagementFactory"
+                   factoryMethod="getPlatformMBeanServer"/>
+   </bean> 
+
+   <!-- The core configuration -->
+   <bean name="Configuration" class="org.hornetq.core.config.impl.FileConfiguration"/>
+
+   <!-- The security manager -->
+   <bean name="HornetQSecurityManager" class="org.hornetq.core.security.impl.HornetQSecurityManagerImpl">
+      <start ignored="true"/>
+      <stop ignored="true"/>
+   </bean>
+
+   <!-- The core server -->
+   <bean name="HornetQServer" class="org.hornetq.core.server.impl.HornetQServerImpl">
+      <constructor>
+         <parameter>
+            <inject bean="Configuration"/>
+         </parameter>
+         <parameter>
+            <inject bean="MBeanServer"/>
+         </parameter>
+         <parameter>
+            <inject bean="HornetQSecurityManager"/>
+         </parameter>        
+      </constructor>
+      <start ignored="true"/>
+      <stop ignored="true"/>
+   </bean>
+   
+   <!-- The JMS server -->
+   <bean name="JMSServerManager" class="org.hornetq.jms.server.impl.JMSServerManagerImpl">
+      <constructor>         
+         <parameter>
+            <inject bean="HornetQServer"/>
+         </parameter>
+      </constructor>
+   </bean>
+
+</deployment>

Added: trunk/examples/jms/applet/server0/hornetq-configuration.xml
===================================================================
--- trunk/examples/jms/applet/server0/hornetq-configuration.xml	                        (rev 0)
+++ trunk/examples/jms/applet/server0/hornetq-configuration.xml	2009-08-26 14:21:01 UTC (rev 7918)
@@ -0,0 +1,33 @@
+<configuration xmlns="urn:hornetq"
+            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-configuration.xsd">
+
+   <!-- Connectors -->
+   <connectors>
+      <connector name="netty-connector">
+         <factory-class>org.hornetq.integration.transports.netty.NettyConnectorFactory</factory-class>         
+      </connector>
+   </connectors>
+   
+   <!-- Acceptors -->
+   <acceptors>
+      <acceptor name="netty-acceptor">
+         <factory-class>org.hornetq.integration.transports.netty.NettyAcceptorFactory</factory-class>         
+      </acceptor>
+   </acceptors>
+
+   <!-- Other config -->
+
+   <security-settings>
+      <!--security for example topic-->
+      <security-setting match="jms.topic.exampleTopic">
+         <permission type="createDurableQueue" roles="guest"/>
+         <permission type="deleteDurableQueue" roles="guest"/>
+         <permission type="createTempQueue" roles="guest"/>
+         <permission type="deleteTempQueue" roles="guest"/>
+         <permission type="consume" roles="guest"/>
+         <permission type="send" roles="guest"/>
+      </security-setting>
+   </security-settings>
+   
+</configuration>

Added: trunk/examples/jms/applet/server0/hornetq-jms.xml
===================================================================
--- trunk/examples/jms/applet/server0/hornetq-jms.xml	                        (rev 0)
+++ trunk/examples/jms/applet/server0/hornetq-jms.xml	2009-08-26 14:21:01 UTC (rev 7918)
@@ -0,0 +1,17 @@
+<configuration xmlns="urn:hornetq"
+            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-jms.xsd">
+   <!--the connection factory used by the example-->
+   <connection-factory name="ConnectionFactory">
+      <connector-ref connector-name="netty-connector"/>
+      <entries>
+         <entry name="ConnectionFactory"/>
+      </entries>
+   </connection-factory>
+
+   <!--the topic used by the example-->
+   <topic name="exampleTopic">
+      <entry name="/topic/exampleTopic"/>
+   </topic>
+
+</configuration>
\ No newline at end of file

Added: trunk/examples/jms/applet/server0/hornetq-users.xml
===================================================================
--- trunk/examples/jms/applet/server0/hornetq-users.xml	                        (rev 0)
+++ trunk/examples/jms/applet/server0/hornetq-users.xml	2009-08-26 14:21:01 UTC (rev 7918)
@@ -0,0 +1,7 @@
+<configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+            xsi:schemaLocation="urn:hornetq /schema/hornetq-users.xsd">
+   <!-- the default user.  this is used where username is null-->
+   <defaultuser name="guest" password="guest">
+      <role name="guest"/>
+   </defaultuser>
+</configuration>
\ No newline at end of file

Added: trunk/examples/jms/applet/src/org/hornetq/jms/example/AppletExample.java
===================================================================
--- trunk/examples/jms/applet/src/org/hornetq/jms/example/AppletExample.java	                        (rev 0)
+++ trunk/examples/jms/applet/src/org/hornetq/jms/example/AppletExample.java	2009-08-26 14:21:01 UTC (rev 7918)
@@ -0,0 +1,286 @@
+/*
+ * Copyright 2009 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.jms.example;
+
+import java.awt.Color;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.Destination;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+import javax.swing.BorderFactory;
+import javax.swing.JApplet;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTextArea;
+import javax.swing.SwingUtilities;
+
+import org.hornetq.core.client.impl.ClientSessionFactoryImpl;
+import org.hornetq.core.config.TransportConfiguration;
+import org.hornetq.integration.transports.netty.NettyConnectorFactory;
+import org.hornetq.jms.HornetQQueue;
+import org.hornetq.jms.HornetQTopic;
+import org.hornetq.jms.client.HornetQConnectionFactory;
+
+/**
+ * A AppletExample
+ *
+ * @author <a href="mailto:jmesnil at redaht.com>Jeff Mesnil</a>
+ *
+ *
+ */
+public class AppletExample extends JApplet implements ActionListener
+{
+
+   // Constants -----------------------------------------------------
+
+   // Attributes ----------------------------------------------------
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   private Destination destination;
+
+   private Connection connection;
+
+   private MessageProducer producer;
+
+   private MessageConsumer consumer;
+
+   private JTextArea display;
+
+   private JButton sendButton;
+
+   private Session session;
+
+   @Override
+   public void init()
+   {
+      super.init();
+
+      try
+      {
+         SwingUtilities.invokeAndWait(new Runnable()
+         {
+            public void run()
+            {
+               createGUI();
+            }
+         });
+      }
+      catch (Exception e)
+      {
+         System.err.println("createGUI didn't successfully complete");
+      }
+
+      Map<String, Object> params = new HashMap<String, Object>();
+      TransportConfiguration connector = new TransportConfiguration(NettyConnectorFactory.class.getName(), params);
+      ClientSessionFactoryImpl sf = new ClientSessionFactoryImpl(connector);
+      ConnectionFactory cf = new HornetQConnectionFactory(sf);
+      destination = new HornetQTopic("exampleTopic");
+
+      try
+      {
+         connection = cf.createConnection();
+         session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+         producer = session.createProducer(destination);
+         consumer = session.createConsumer(destination);
+         consumer.setMessageListener(new MessageListener()
+         {
+            public void onMessage(final Message msg)
+            {
+               try
+               {
+                  SwingUtilities.invokeAndWait(new Runnable()
+                  {
+                     public void run()
+                     {
+                        try
+                        {
+                           display.setText(display.getText() + "\n" + ((TextMessage)msg).getText());
+                        }
+                        catch (JMSException e)
+                        {
+                           e.printStackTrace();
+                        }
+                     }
+                  });
+               }
+               catch (Exception e)
+               {
+                  e.printStackTrace();
+               }
+            }
+         });
+      }
+      catch (JMSException e)
+      {
+         e.printStackTrace();
+      }
+   }
+
+   @Override
+   public void start()
+   {
+      super.start();
+
+      try
+      {
+         connection.start();
+      }
+      catch (JMSException e)
+      {
+         e.printStackTrace();
+      }
+   }
+
+   @Override
+   public void stop()
+   {
+      System.out.println("close connection");
+      if (connection != null)
+      {
+         try
+         {
+            connection.close();
+         }
+         catch (JMSException e)
+         {
+            e.printStackTrace();
+         }
+      }
+
+      super.stop();
+
+   }
+
+   // Public --------------------------------------------------------
+
+   public static void main(String[] args)
+   {
+
+      final AppletExample applet = new AppletExample();
+      applet.init();
+
+      JFrame frame = new JFrame("Applet Example");
+      frame.getContentPane().add(applet);
+
+      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+      frame.pack();
+      frame.setVisible(true);
+
+      applet.start();
+      Runtime.getRuntime().addShutdownHook(new Thread()
+      {
+         @Override
+         public void run()
+         {
+            applet.stop();
+         }
+      });
+   }
+
+   public void actionPerformed(ActionEvent e)
+   {
+      try
+      {
+         producer.send(session.createTextMessage((new Date()).toString()));
+      }
+      catch (JMSException e1)
+      {
+         e1.printStackTrace();
+      }
+   }
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   private void createGUI()
+   {
+      JPanel contentPane = new JPanel(new GridBagLayout());
+      GridBagConstraints c = new GridBagConstraints();
+      int numColumns = 3;
+
+      JLabel l1 = new JLabel("Received Messages:", JLabel.CENTER);
+      c.gridx = 0;
+      c.gridy = 0;
+      c.anchor = GridBagConstraints.SOUTH;
+      c.gridwidth = numColumns;
+      contentPane.add(l1, c);
+
+      display = new JTextArea(5, 20);
+      JScrollPane scrollPane = new JScrollPane(display);
+      display.setEditable(false);
+      display.setForeground(Color.gray);
+      c.gridy = 1;
+      c.gridwidth = numColumns;
+      c.anchor = GridBagConstraints.CENTER;
+      c.weighty = 1.0;
+      c.fill = GridBagConstraints.BOTH;
+      contentPane.add(scrollPane, c);
+
+      sendButton = new JButton("Send");
+      c.gridy = 2;
+      c.gridwidth = 1;
+      c.anchor = GridBagConstraints.SOUTH;
+      c.weighty = 0.0;
+      c.fill = GridBagConstraints.NONE;
+      contentPane.add(sendButton, c);
+
+      sendButton.addActionListener(this);
+
+      JButton clearButton = new JButton("Clear");
+      c.gridx = 2;
+      c.weightx = 0.0;
+      c.anchor = GridBagConstraints.SOUTHEAST;
+      c.fill = GridBagConstraints.NONE;
+      contentPane.add(clearButton, c);
+
+      clearButton.addActionListener(new ActionListener()
+      {
+         public void actionPerformed(ActionEvent e)
+         {
+            display.setText("");
+         }
+      });
+
+      // Finish setting up the content pane and its border.
+      contentPane.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),
+                                                               BorderFactory.createEmptyBorder(5, 20, 5, 10)));
+      setContentPane(contentPane);
+   }
+   
+   // Inner classes -------------------------------------------------
+
+}

Added: trunk/examples/jms/applet/src/org/hornetq/jms/example/HttpStaticFileServer.java
===================================================================
--- trunk/examples/jms/applet/src/org/hornetq/jms/example/HttpStaticFileServer.java	                        (rev 0)
+++ trunk/examples/jms/applet/src/org/hornetq/jms/example/HttpStaticFileServer.java	2009-08-26 14:21:01 UTC (rev 7918)
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2009 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.jms.example;
+
+import java.net.InetSocketAddress;
+import java.util.concurrent.Executors;
+
+import org.hornetq.common.example.HornetQExample;
+import org.jboss.netty.bootstrap.ServerBootstrap;
+import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
+
+/**
+ * A HttpServer
+ *
+ * * @author The Netty Project (netty-dev at lists.jboss.org)
+ * @author Trustin Lee (tlee at redhat.com)
+ * @author <a href="mailto:jmesnil at redhat.com>Jeff Mesnil</a>
+ *
+ *
+ */
+public class HttpStaticFileServer extends HornetQExample
+{
+
+   public static void main(String[] args)
+   {
+      new HttpStaticFileServer().run(args);
+   }
+   
+   @Override
+   public boolean runExample() throws Exception
+   {
+      // Configure the server.
+      ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
+                                                                                        Executors.newCachedThreadPool()));
+      // Set up the event pipeline factory.
+      bootstrap.setPipelineFactory(new HttpStaticFileServerPipelineFactory());
+      // Bind and start to accept incoming connections.
+      bootstrap.bind(new InetSocketAddress(8088));
+
+      System.out.println("HTTP server ready to server on 8088");
+
+      System.out.println("open http://127.0.0.1:8088/applet.html to use the Applet");
+      
+      while (true)
+      {
+         Thread.sleep(100);         
+      }
+      
+   }
+
+   // Attributes ----------------------------------------------------
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   // Public --------------------------------------------------------
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+
+}

Added: trunk/examples/jms/applet/src/org/hornetq/jms/example/HttpStaticFileServerHandler.java
===================================================================
--- trunk/examples/jms/applet/src/org/hornetq/jms/example/HttpStaticFileServerHandler.java	                        (rev 0)
+++ trunk/examples/jms/applet/src/org/hornetq/jms/example/HttpStaticFileServerHandler.java	2009-08-26 14:21:01 UTC (rev 7918)
@@ -0,0 +1,170 @@
+/*
+ * Copyright 2009 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.jms.example;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.RandomAccessFile;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+
+import org.jboss.netty.buffer.ChannelBuffers;
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.ChannelFuture;
+import org.jboss.netty.channel.ChannelFutureListener;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.channel.ChannelPipelineCoverage;
+import org.jboss.netty.channel.ExceptionEvent;
+import org.jboss.netty.channel.MessageEvent;
+import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
+import org.jboss.netty.handler.codec.frame.TooLongFrameException;
+import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
+import org.jboss.netty.handler.codec.http.HttpHeaders;
+import org.jboss.netty.handler.codec.http.HttpMethod;
+import org.jboss.netty.handler.codec.http.HttpRequest;
+import org.jboss.netty.handler.codec.http.HttpResponse;
+import org.jboss.netty.handler.codec.http.HttpResponseStatus;
+import org.jboss.netty.handler.codec.http.HttpVersion;
+import org.jboss.netty.handler.stream.ChunkedFile;
+
+/**
+ * A HttpStaticFileServerHandler
+ *
+ * @author The Netty Project (netty-dev at lists.jboss.org)
+ * @author Trustin Lee (tlee at redhat.com)
+ * @author <a href="mailto:jmesnil at redhat.com>Jeff Mesnil</a>
+ *
+ *
+ */
+ at ChannelPipelineCoverage("one")
+ public class HttpStaticFileServerHandler extends SimpleChannelUpstreamHandler {
+ 
+     @Override
+     public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
+         HttpRequest request = (HttpRequest) e.getMessage();
+         if (request.getMethod() != HttpMethod.GET) {
+             sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
+             return;
+         }
+ 
+         if (request.isChunked()) {
+             sendError(ctx, HttpResponseStatus.BAD_REQUEST);
+             return;
+         }
+ 
+         String path = sanitizeUri(request.getUri());
+         if (path == null) {
+             sendError(ctx, HttpResponseStatus.FORBIDDEN);
+             return;
+         }
+ 
+         File file = new File(path);
+         if (file.isHidden() || !file.exists()) {
+             sendError(ctx, HttpResponseStatus.NOT_FOUND);
+             return;
+         }
+         if (!file.isFile()) {
+             sendError(ctx, HttpResponseStatus.FORBIDDEN);
+             return;
+         }
+ 
+         RandomAccessFile raf;
+         try {
+             raf = new RandomAccessFile(file, "r");
+         } catch (FileNotFoundException fnfe) {
+             sendError(ctx, HttpResponseStatus.NOT_FOUND);
+             return;
+         }
+         long fileLength = raf.length();
+ 
+         HttpResponse response = new DefaultHttpResponse(
+                 HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
+         response.setHeader(
+                 HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(fileLength));
+ 
+         Channel ch = e.getChannel();
+ 
+         // Write the initial line and the header.
+         ch.write(response);
+ 
+         // Write the content.
+         ChannelFuture writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
+ 
+         // Decide whether to close the connection or not.
+         boolean close =
+             HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.getHeader(HttpHeaders.Names.CONNECTION)) ||
+             request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) &&
+             !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.getHeader(HttpHeaders.Names.CONNECTION));
+ 
+         if (close) {
+             // Close the connection when the whole content is written out.
+             writeFuture.addListener(ChannelFutureListener.CLOSE);
+         }
+     }
+ 
+     @Override
+     public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
+             throws Exception {
+         Channel ch = e.getChannel();
+         Throwable cause = e.getCause();
+         if (cause instanceof TooLongFrameException) {
+             sendError(ctx, HttpResponseStatus.BAD_REQUEST);
+             return;
+         }
+ 
+         cause.printStackTrace();
+         if (ch.isConnected()) {
+             sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
+         }
+     }
+ 
+     private String sanitizeUri(String uri) {
+         // Decode the path.
+         try {
+             uri = URLDecoder.decode(uri, "UTF-8");
+         } catch (UnsupportedEncodingException e) {
+             try {
+                 uri = URLDecoder.decode(uri, "ISO-8859-1");
+             } catch (UnsupportedEncodingException e1) {
+                 throw new Error();
+             }
+         }
+ 
+         // Convert file separators.
+         uri = uri.replace('/', File.separatorChar);
+ 
+         // Simplistic dumb security check.
+         // You will have to do something serious in the production environment.
+         if (uri.contains(File.separator + ".") ||
+             uri.contains("." + File.separator) ||
+             uri.startsWith(".") || uri.endsWith(".")) {
+             return null;
+         }
+ 
+         // Convert to absolute path.
+         return System.getProperty("user.dir") + File.separator + uri;
+     }
+ 
+     private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
+         HttpResponse response = new DefaultHttpResponse(
+                 HttpVersion.HTTP_1_1, status);
+         response.setHeader(
+                 HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
+         response.setContent(ChannelBuffers.copiedBuffer(
+                 "Failure: " + status.toString() + "\r\n", "UTF-8"));
+ 
+         // Close the connection as soon as the error message is sent.
+         ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
+     }
+}
\ No newline at end of file

Added: trunk/examples/jms/applet/src/org/hornetq/jms/example/HttpStaticFileServerPipelineFactory.java
===================================================================
--- trunk/examples/jms/applet/src/org/hornetq/jms/example/HttpStaticFileServerPipelineFactory.java	                        (rev 0)
+++ trunk/examples/jms/applet/src/org/hornetq/jms/example/HttpStaticFileServerPipelineFactory.java	2009-08-26 14:21:01 UTC (rev 7918)
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2009 Red Hat, Inc.
+ * Red Hat licenses this file to you under the Apache License, version
+ * 2.0 (the "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ * implied.  See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package org.hornetq.jms.example;
+
+import static org.jboss.netty.channel.Channels.pipeline;
+
+import org.jboss.netty.channel.ChannelPipeline;
+import org.jboss.netty.channel.ChannelPipelineFactory;
+import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
+import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
+import org.jboss.netty.handler.stream.ChunkedWriteHandler;
+
+/**
+ * A HttpStaticFileServerPipelineFactory
+ *
+ * @author The Netty Project (netty-dev at lists.jboss.org)
+ * @author Trustin Lee (tlee at redhat.com)
+ * @author <a href="mailto:jmesnil at redhat.com>Jeff Mesnil</a>
+ *
+ *
+ */
+public class HttpStaticFileServerPipelineFactory implements ChannelPipelineFactory
+{
+   public ChannelPipeline getPipeline() throws Exception
+   {
+      // Create a default pipeline implementation.
+      ChannelPipeline pipeline = pipeline();
+
+      pipeline.addLast("decoder", new HttpRequestDecoder());
+      pipeline.addLast("encoder", new HttpResponseEncoder());
+      pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
+
+      pipeline.addLast("handler", new HttpStaticFileServerHandler());
+      return pipeline;
+   }
+
+   // Constants -----------------------------------------------------
+
+   // Attributes ----------------------------------------------------
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   // Public --------------------------------------------------------
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+
+}



More information about the hornetq-commits mailing list