<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
  <!ENTITY % images_ent SYSTEM "images.ent"> 
  %images_ent;
] >
<book lang="en">
  <bookinfo>
    <title>TorqueBox Getting Started Guide</title>

    <releaseinfo>${project.version}</releaseinfo>

    <authorgroup>
      <corpauthor>The TorqueBox Project</corpauthor>
    </authorgroup>
  </bookinfo>

  <toc></toc>

  <chapter id="first-steps">
    <title>First Steps</title>

    <para>
      Choose the section below to follow based on your development
      environment - Windows users should follow <xref
      linkend="first-steps-windows"/>, RVM users should follow <xref
      linkend="first-steps-rvm"/>, and regular Mac or Linux users
      should follow <xref linkend="first-steps-mac-linux"/>.
    </para>

    <section id="first-steps-mac-linux">
      <title>First Steps on Mac / Linux</title>

      <para>
        If you use Ruby Version Manager (RVM), be sure to follow the
        <xref linkend="first-steps-rvm"/> instructions and not the
        generic Mac / Linux instructions.
      </para>

      <section>
        <title>Your First Rails Application</title>

        <para>
          Ensure you have Java 6 or above installed then download and
          extract the TorqueBox binary distribution and set a few
          environment variables.

          <screen><prompt>$</prompt> <command>wget http://torquebox.org/release/org/torquebox/torquebox-dist/${project.version}/torquebox-dist-${project.version}-bin.zip</command>
...
2012-09-13 09:35:56 (1.61 MB/s) - `torquebox-dist-${project.version}-bin.zip' saved [152039457/152039457]

<prompt>$</prompt> <command>unzip torquebox-dist-${project.version}-bin.zip -d ~ </command>
...
  inflating: torquebox-2.1.1/Rakefile
<prompt>$</prompt> <command>export TORQUEBOX_HOME=~/torquebox-${project.version}</command>
<prompt>$</prompt> <command>export JBOSS_HOME=$TORQUEBOX_HOME/jboss</command>
<prompt>$</prompt> <command>export JRUBY_HOME=$TORQUEBOX_HOME/jruby</command>
<prompt>$</prompt> <command>export PATH=$JRUBY_HOME/bin:$PATH</command></screen>

          You'll likely want to place the exports somewhere that gets
          loaded automatically - <filename>~/.bashrc</filename>,
          <filename>~/.bash_profile</filename>, or wherever your
          operating system suggests placing user-specific environment
          variables.
        </para>

        <para>
          Install Rails and create a new Rails example application.

          <screen><prompt>$</prompt> <command>mkdir -p ~/torquebox_examples/rails_example</command>
<prompt>$</prompt> <command>cd ~/torquebox_examples/rails_example</command>
<prompt>$</prompt> <command>gem install rails</command>
...
Successfully installed rails-3.2.8
27 gems installed
<prompt>$</prompt> <command>rails new .</command>
...
Using rails (3.2.8) 
Installing sass (3.2.1) 
Installing sass-rails (3.2.5) 
Installing therubyrhino_jar (1.7.4) 
Installing therubyrhino (2.0.1) 
Installing uglifier (1.3.0) 
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.</screen>
          <note>
            <title>Bundler and jruby-openssl</title>
            <para>
              Some versions of JRuby, Bundler, and jruby-openssl don't
              play well together so if you get an error when Rails
              tries to run <command>bundle install</command> regarding
              jruby-openssl, edit the <filename>Gemfile</filename> to
              change the source line from https to http and manually
              run <command>bundle install</command> afterwards.
            </para>
          </note>
        </para>

        <para>
          Add a simple scaffolded resource, deploy it to TorqueBox,
          and run TorqueBox.

          <screen><prompt>$</prompt> <command>rails g scaffold post title body:text</command>
...
      create      app/assets/stylesheets/posts.css.scss
      invoke  scss
      create      app/assets/stylesheets/scaffolds.css.scss
<prompt>$</prompt> <command>rake db:migrate</command>
==  CreatePosts: migrating ====================================================
-- create_table(:posts)
   -> 0.0060s
   -> 0 rows
==  CreatePosts: migrated (0.0080s) ===========================================

<prompt>$</prompt> <command>torquebox deploy</command>
Deployed: rails_example-knob.yml
    into: /Users/someone/torquebox-${project.version}/jboss/standalone/deployments
<prompt>$</prompt> <command>torquebox run </command>
...
15:59:28,053 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018559: Deployed "rails_example-knob.yml"</screen>
        </para>

        <para>
          Open <ulink url="http://localhost:8080"/> in your browser
          and you'll be greeted with the Rails "Welcome aboard"
          page. Navigate to <ulink
          url="http://localhost:8080/posts/"/> to see your scaffolded
          resource.
        </para>

        <para>
          Now edit
          <filename>~/torquebox_examples/rails_example/app/views/posts/index.html.erb</filename>
          then refresh the posts page in your browser and see your
          changes. Changes to your Rails application show up
          immediately in the browser, as expected. When you're done,
          press CTRL+C in the terminal to stop TorqueBox before
          continuing with the next steps.
        </para>
      </section>

      <section>
        <title>Subsequent Applications</title>

        <para>
          Deploying multiple applications to TorqueBox is
          straightforward, but let's walk through the required steps.
          We'll create a Rack application to go with our Rails example
          application created earlier. If TorqueBox is still running
          stop it with CTRL+C in its terminal window before following
          the steps below.

      <screen><prompt>$</prompt> <command>mkdir -p ~/torquebox_examples/rack_example</command>
<prompt>$</prompt> <command>cd ~/torquebox_examples/rack_example</command>
<prompt>$</prompt> <command>gem install rack</command>
Fetching: rack-1.4.1.gem (100%)
Successfully installed rack-1.4.1
1 gem installed
</screen>

          Now create a <filename>config.ru</filename> for our example
          rack application.
          <example>
            <title><filename>~/torquebox_examples/rack_example/config.ru</filename></title>
            <programlisting>app = lambda { |env|
  [200, { 'Content-Type' => 'text/html' }, "Hello from Rack\n" ]
}
run app</programlisting>
          </example>

          Deploy the Rack application at a context-path of "/rack"
          since we already have the Rails application deployed at the
          root context.

        <screen><prompt>$</prompt> <command>torquebox deploy --context-path=/rack</command>
Deployed: rack_example-knob.yml
    into: /Users/someone/torquebox-${project.version}/jboss/standalone/deployments</screen>
        </para>

        <para>
          Now you should be able to run TorqueBox and see both
          applications deployed.

        <screen><prompt>$</prompt> <command>torquebox run</command>
...
19:25:38,049 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018559: Deployed "rails_example-knob.yml"
19:25:38,050 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018559: Deployed "rack_example-knob.yml"</screen>

          Visit <ulink url="http://localhost:8080"/> and <ulink
          url="http://localhost:8080/rack/"/> to see that both your
          Rails and Rack applications are deployed and working.
        </para>

        <para>
          Congratulations! You now know all the basics to proceed with
          the rest of this getting started guide when using a Mac or
          Linux.
        </para>

        <para>Continue to <xref linkend="adding-torquebox-features"/>.</para>
      </section>
    </section>

    <section id="first-steps-windows">
      <title>First Steps on Windows</title>

      <section>
        <title>Your First Rails Application</title>

        <para>
          Ensure you have Java 6 or above installed then download
          TorqueBox using your web browser from <ulink
          url="http://torquebox.org/release/org/torquebox/torquebox-dist/${project.version}/torquebox-dist-${project.version}-bin.zip"/>. Right-click
          the downloaded zip in Windows Explorer and select Extract
          All. When prompted for a folder to extract the files to,
          choose your user's home directory (ie
          <filename>C:\Users\someone\</filename>).
        </para>

        <para>
          After TorqueBox is extracted, we need to set a few
          environment variables. Find the Advanced System Settings
          dialog (in Windows 7 this is Control Panel -> System and
          Security -> System -> Advanced System Settings) and click
          the Environment Variables button. We want to add three new
          user environment variables. Add
          <varname>TORQUEBOX_HOME</varname> with a value of
          <filename>%HOME%\torquebox-${project.version}</filename>. Add
          <varname>JBOSS_HOME</varname> with a value of
          <filename>%HOME%\torquebox-${project.version}\jboss</filename>. Add
          <varname>JRUBY_HOME</varname> with a value of
          <filename>%HOME%\torquebox-${project.version}\jruby</filename>. Also modify the
          <varname>Path</varname> environment variable by prepending
          <filename>%JRUBY_HOME%\bin;</filename> to the front of the
          current value. Click the OK button to save and close the
          Environment Variables dialog.
        </para>

        <para>
          Now let's open up a Command Prompt to install Rails and
          create a new Rails example application. You can open a
          Command Prompt by clicking the Windows button in the bottom
          left and typing <filename>cmd</filename> in the search box.

          <screen><prompt>&gt;</prompt> <command>mkdir %HOME%\torquebox_examples\rails_example</command>
<prompt>&gt;</prompt> <command>cd %HOME%\torquebox_examples\rails_example</command>
<prompt>&gt;</prompt> <command>gem install rails</command>
...
Successfully installed rails-3.2.8
27 gems installed
<prompt>&gt;</prompt> <command>rails new .</command>
...
Using rails (3.2.8) 
Installing sass (3.2.1) 
Installing sass-rails (3.2.5) 
Installing therubyrhino_jar (1.7.4) 
Installing therubyrhino (2.0.1) 
Installing uglifier (1.3.0) 
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.</screen>
          <note>
            <title>Bundler and jruby-openssl</title>
            <para>
              Some versions of JRuby, Bundler, and jruby-openssl don't
              play well together so if you get an error when Rails
              tries to run <command>bundle install</command> regarding
              jruby-openssl, edit the <filename>Gemfile</filename> to
              change the source line from https to http and manually
              run <command>bundle install</command> afterwards.
            </para>
          </note>
        </para>

        <para>
          Add a simple scaffolded resource, deploy it to TorqueBox,
          and run TorqueBox.

          <screen><prompt>&gt;</prompt> <command>rails g scaffold post title body:text</command>
...
      create      app/assets/stylesheets/posts.css.scss
      invoke  scss
      create      app/assets/stylesheets/scaffolds.css.scss
<prompt>&gt;</prompt> <command>rake db:migrate</command>
==  CreatePosts: migrating ====================================================
-- create_table(:posts)
   -> 0.0060s
   -> 0 rows
==  CreatePosts: migrated (0.0080s) ===========================================

<prompt>&gt;</prompt> <command>torquebox deploy</command>
Deployed: rails_example-knob.yml
    into: C:\Users\someone\torquebox-${project.version}\jboss\standalone\deployments
<prompt>&gt;</prompt> <command>echo Y | jruby -S torquebox run </command>
...
15:59:28,053 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018559: Deployed "rails_example-knob.yml"</screen>

          <tip>
            <title>Why <command>echo Y</command> and <command>jruby -S</command>?</title>
            <para>
              When stopping TorqueBox via CTRL+C, the Windows Command
              Prompt will ask you if you want to "Terminate batch job
              (Y/N)?". Piping <command>echo Y</command> into the
              command just prevents you from having to answer this
              prompt.

              We prefix the command with <command>jruby -S</command>
              because if we just used <command>echo Y | torquebox
              run</command> there's currently a bug where TorqueBox
              would get stuck in an infinite restart loop upon
              stopping.
            </para>
          </tip>
        </para>

        <para>
          Open <ulink url="http://localhost:8080"/> in your browser
          and you'll be greeted with the Rails "Welcome aboard"
          page. Navigate to <ulink
          url="http://localhost:8080/posts/"/> to see your scaffolded
          resource.
        </para>

        <para>
          Now edit
          <filename>%HOME%\torquebox_examples\rails_example\app\views\posts\index.html.erb</filename>
          then refresh the posts page in your browser and see your
          changes. Changes to your Rails application show up
          immediately in the browser, as expected. When you're done,
          press CTRL+C in the terminal to stop TorqueBox before
          continuing with the next steps.
        </para>
      </section>

      <section>
        <title>Subsequent Applications</title>

        <para>
          Deploying multiple applications to TorqueBox is
          straightforward, but let's walk through the required steps.
          We'll create a Rack application to go with our Rails example
          application created earlier. If TorqueBox is still running
          stop it with CTRL+C in its terminal window before following
          the steps below.

      <screen><prompt>&gt;</prompt> <command>mkdir %HOME%\torquebox_examples\rack_example</command>
<prompt>&gt;</prompt> <command>cd %HOME%\torquebox_examples\rack_example</command>
<prompt>&gt;</prompt> <command>gem install rack</command>
Fetching: rack-1.4.1.gem (100%)
Successfully installed rack-1.4.1
1 gem installed
</screen>

          Now create a <filename>config.ru</filename> for our example
          rack application.
          <example>
            <title><filename>%HOME%\torquebox_examples\rack_example\config.ru</filename></title>
            <programlisting>app = lambda { |env|
  [200, { 'Content-Type' => 'text/html' }, "Hello from Rack\n" ]
}
run app</programlisting>
          </example>

          Deploy the Rack application at a context-path of "/rack"
          since we already have the Rails application deployed at the
          root context.

        <screen><prompt>&gt;</prompt> <command>torquebox deploy --context-path=/rack</command>
Deployed: rack_example-knob.yml
    into: C:\Users\someone\torquebox-${project.version}\jboss\standalone\deployments</screen>
        </para>

        <para>
          Now you should be able to run TorqueBox and see both
          applications deployed.

        <screen><prompt>&gt;</prompt> <command>echo Y | jruby -S torquebox run</command>
...
19:25:38,049 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018559: Deployed "rails_example-knob.yml"
19:25:38,050 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018559: Deployed "rack_example-knob.yml"</screen>

          Visit <ulink url="http://localhost:8080"/> and <ulink
          url="http://localhost:8080/rack/"/> to see that both your
          Rails and Rack applications are deployed and working.
        </para>

        <para>
          Congratulations! You now know all the basics to proceed with
          the rest of this getting started guide when using
          Windows. The filesystem paths and command prompts shown in
          future chapters won't be Windows-specific, so be sure to
          translate any paths to the appropriate format before
          executing the example commands.
        </para>

        <para>Continue to <xref linkend="adding-torquebox-features"/>.</para>

      </section>

    </section>

    <section id="first-steps-rvm">
      <title>First Steps with RVM</title>

      <section>
        <title>Your First Rails Application</title>

        <para>
          Ensure you have a recent JRuby installed then install the
          <varname>torquebox-server</varname> gem into the global
          gemset.

        <screen><prompt>$</prompt> <command>rvm install jruby-${version.jruby}</command>
<prompt>$</prompt> <command>rvm use jruby-${version.jruby}@global</command>
<prompt>$</prompt> <command>gem install torquebox-server</command></screen>
        </para>

        <para>
          Create a directory and project-specific gemset for our
          example application.

        <screen><prompt>$</prompt> <command>mkdir -p ~/torquebox_examples/rails_example</command>
<prompt>$</prompt> <command>cd ~/torquebox_examples/rails_example</command>
<prompt>$</prompt> <command>rvm --rvmrc --create jruby-${version.jruby}@tb_rails_example</command></screen>
        </para>

        <para>
          Change to the Rails example directory, trust the generated
          .rvmrc file when prompted, and install Rails.

        <screen><prompt>$</prompt> <command>cd ~/torquebox_examples/rails_example</command>
====================================================================================
= NOTICE                                                                           =
====================================================================================
= RVM has encountered a new or modified .rvmrc file in the current directory       =
= This is a shell script and therefore may contain any shell commands.             =
=                                                                                  =
= Examine the contents of this file carefully to be sure the contents are          =
= safe before trusting it! ( Choose v[iew] below to view the contents )            =
====================================================================================
Do you wish to trust this .rvmrc file? (/Users/someone/torquebox_examples/rails_example/.rvmrc)
y[es], n[o], v[iew], c[ancel]> y
<prompt>$</prompt> <command>rvm gemset list</command>

gemsets for jruby-${version.jruby} (found in /Users/someone/.rvm/gems/jruby-${version.jruby})
   global
=> tb_rails_example

<prompt>$</prompt> <command>gem install rails</command>
...
Successfully installed rails-3.2.8
27 gems installed</screen>
        </para>

        <para>
          Create a new Rails application, add a simple scaffolded
          resource, deploy it to TorqueBox, and run TorqueBox.

        <screen><prompt>$</prompt> <command>rails new .</command>
...
Using rails (3.2.8) 
Installing sass (3.2.1) 
Installing sass-rails (3.2.5) 
Installing therubyrhino_jar (1.7.4) 
Installing therubyrhino (2.0.1) 
Installing uglifier (1.3.0) 
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
<prompt>$</prompt> <command>rails g scaffold post title body:text</command>
...
      create      app/assets/stylesheets/posts.css.scss
      invoke  scss
      create      app/assets/stylesheets/scaffolds.css.scss
<prompt>$</prompt> <command>rake db:migrate</command>
==  CreatePosts: migrating ====================================================
-- create_table(:posts)
   -> 0.0060s
   -> 0 rows
==  CreatePosts: migrated (0.0080s) ===========================================

<prompt>$</prompt> <command>torquebox deploy</command>
Deployed: rails_example-knob.yml
    into: /Users/someone/.rvm/gems/jruby-${version.jruby}@global/gems/torquebox-server-${project.version}-java/jboss/standalone/deployments
<prompt>$</prompt> <command>torquebox run </command>
...
15:59:28,053 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018559: Deployed "rails_example-knob.yml"</screen>
        </para>

        <para>
          Open <ulink url="http://localhost:8080"/> in your browser
          and you'll be greeted with the Rails "Welcome aboard"
          page. Navigate to <ulink
          url="http://localhost:8080/posts/"/> to see your scaffolded
          resource.
        </para>

        <para>
          Now edit
          <filename>~/torquebox_examples/rails_example/app/views/posts/index.html.erb</filename>
          then refresh the posts page in your browser and see your
          changes. Changes to your Rails application show up
          immediately in the browser, as expected. When you're done,
          press CTRL+C in the terminal to stop TorqueBox before
          continuing with the next steps.
        </para>

        <para>
          When you want to take advantage of TorqueBox-specific
          features, like we'll do in subsequent chapters, you'll need
          the <varname>torquebox</varname> gem in your application's
          Gemfile. However, since we're using
          <varname>torquebox-server</varname> under RVM to install
          TorqueBox, you'll want to ensure this gem is in the Gemfile
          for every application as well. If it's not you'll receive
          errors trying to use the <command>torquebox</command>
          because bundler will be unable to find the
          <varname>torquebox-server</varname> gem.

          <example>
            <title><filename>~/torquebox_examples/rails_example/Gemfile</filename></title>
            <programlisting>source 'https://rubygems.org'

gem 'rails', '3.2.8'

gem 'activerecord-jdbcsqlite3-adapter'
gem 'jruby-openssl'
gem 'json'

group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'
  gem 'therubyrhino'
  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

gem 'torquebox', '~> ${project.version}'
gem 'torquebox-server', '~> ${project.version}'</programlisting>
          </example>
        </para>

      </section>

      <section>
        <title>Subsequent Applications</title>

        <para>
          Deploying multiple applications to TorqueBox when using RVM
          and project-specific gemsets requires a small amount of
          extra work. To walk through the required steps, let's create
          a second Rack application to go with our Rails example
          application created earlier. If TorqueBox is still running
          stop it with CTRL+C in its terminal window before following
          the steps below.

      <screen><prompt>$</prompt> <command>mkdir -p ~/torquebox_examples/rack_example</command>
<prompt>$</prompt> <command>cd ~/torquebox_examples/rack_example</command>
<prompt>$</prompt> <command>rvm --rvmrc --create jruby-${version.jruby}@tb_rack_example</command>
<prompt>$</prompt> <command>cd ~/torquebox_examples/rack_example</command>
====================================================================================
= NOTICE                                                                           =
====================================================================================
= RVM has encountered a new or modified .rvmrc file in the current directory       =
= This is a shell script and therefore may contain any shell commands.             =
=                                                                                  =
= Examine the contents of this file carefully to be sure the contents are          =
= safe before trusting it! ( Choose v[iew] below to view the contents )            =
====================================================================================
Do you wish to trust this .rvmrc file? (/Users/someone/torquebox_examples/rack_example/.rvmrc)
y[es], n[o], v[iew], c[ancel]> y
<prompt>$</prompt> <command>rvm gemset list</command>

gemsets for jruby-${version.jruby} (found in /Users/someone/.rvm/gems/jruby-${version.jruby})
   global
=> tb_rack_example
   tb_rails_example

<prompt>$</prompt> <command>gem install rack</command>
Fetching: rack-1.4.1.gem (100%)
Successfully installed rack-1.4.1
1 gem installed
</screen>

          Now create a <filename>config.ru</filename> for our example
          rack application.
          <example>
            <title><filename>~/torquebox_examples/rack_example/config.ru</filename></title>
            <programlisting>app = lambda { |env|
  [200, { 'Content-Type' => 'text/html' }, "Hello from Rack\n" ]
}
run app</programlisting>
          </example>

          Deploy the Rack application at a context-path of "/rack"
          since we already have the Rails application deployed at the
          root context.

        <screen><prompt>$</prompt> <command>torquebox deploy --context-path=/rack</command>
Deployed: rack_example-knob.yml
    into: /Users/someone/.rvm/gems/jruby-${version.jruby}@global/gems/torquebox-server-${project.version}-java/jboss/standalone/deployments</screen>
        </para>

        <para>
          Now that two applications are deployed to TorqueBox, each
          with separate RVM gemsets, we hit an issue that trips up
          most users of RVM and TorqueBox. TorqueBox runs as a single
          process but RVM is really designed to have a separate
          process per project for gemsets to work out of the box. We
          can work around this by emulating the environment variables
          RVM sets when reading our <filename>.rvmrc</filename> in a
          <filename>torquebox.rb</filename> file for each application.

          <example>
            <title><filename>~/torquebox_examples/rack_example/torquebox.rb</filename></title>
            <programlisting>TorqueBox.configure do
  environment do
    GEM_HOME "#{ENV['rvm_path']}/gems/jruby-${version.jruby}@tb_rack_example"
    GEM_PATH "#{ENV['rvm_path']}/gems/jruby-${version.jruby}@tb_rack_example:#{ENV['rvm_path']}/gems/jruby-${version.jruby}@global"
  end
end</programlisting>
          </example>

          <example>
            <title><filename>~/torquebox_examples/rails_example/config/torquebox.rb</filename></title>
            <programlisting>TorqueBox.configure do
  environment do
    GEM_HOME "#{ENV['rvm_path']}/gems/jruby-${version.jruby}@tb_rails_example"
    GEM_PATH "#{ENV['rvm_path']}/gems/jruby-${version.jruby}@tb_rails_example:#{ENV['rvm_path']}/gems/jruby-${version.jruby}@global"
  end
end</programlisting>
          </example>

          Now you should be able to run TorqueBox and see both
          applications deployed.

        <screen><prompt>$</prompt> <command>torquebox run</command>
...
19:25:38,049 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018559: Deployed "rails_example-knob.yml"
19:25:38,050 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018559: Deployed "rack_example-knob.yml"</screen>

          Visit <ulink url="http://localhost:8080"/> and <ulink
          url="http://localhost:8080/rack/"/> to see that both your
          Rails and Rack applications are deployed and working.
        </para>

        <para>
          Congratulations! You now know all the basics to proceed with
          the rest of this getting started guide when using RVM. The
          most important thing to remember is to add the
          <filename>torquebox.rb</filename> that sets the
          <varname>GEM_HOME</varname> and <varname>GEM_PATH</varname>
          environment variables for each application that uses a
          project-specific gemset.
        </para>

        <para>Continue to <xref linkend="adding-torquebox-features"/>.</para>
      </section>
    </section>

  </chapter>

  <chapter id="adding-torquebox-features">
    <title>Adding TorqueBox Features</title>

    <para>
      This chapter builds upon the simple Rails application we created
      in <xref linkend="first-steps"/> by modifying it to take
      advantage of TorqueBox features.
    </para>

    <section id="features-rails-template">
      <title>TorqueBox Rails Template</title>

      <para>
        TorqueBox ships with a Rails template that we can use to
        automatically add <filename>torquebox</filename> to the
        Gemfile, convert the session store to the optional TorqueBox
        clustered session storage, setup all ActiveRecord objects to
        have <classname>TorqueBox::Backgroundable</classname> methods
        available, and add some TorqueBox-specific Rake tasks.

        <screen><prompt>$</prompt> <command>cd ~/torquebox_examples/rails_example</command>
<prompt>$</prompt> <command>torquebox rails</command>
       apply  /Users/someone/torquebox-${project.version}/share/rails/template.rb
     gemfile    torquebox (${project.version})
      remove    config/initializers/session_store.rb
 initializer    session_store.rb
 initializer    active_record_backgroundable.rb
    rakefile    torquebox.rake</screen>
      </para>
    </section>

    <section id="features-backgroundable">
      <title>Running Tasks in the Background</title>

      <para>
        To illustrate how TorqueBox makes it effortless to run
        long-running tasks in the background, let's first add a
        long-running task to our <classname>Post</classname>
        model. After each <classname>Post</classname> is created, lets
        publish a message to our favorite social network linking to
        that post. For simplicitly we'll just log a message and sleep
        for a few seconds to simulate the publish.

        <example>
          <title><filename>~/torquebox_examples/rails_example/app/models/post.rb</filename></title>
          <programlisting><![CDATA[class Post < ActiveRecord::Base
  attr_accessible :body, :title

  after_create :publish_to_social_network

  def publish_to_social_network
    puts "Publishing '#{title}' to our favorite social network"
    sleep(5)
    puts "Post published"
  end
end]]></programlisting>
        </example>

        Start TorqueBox if it isn't already running via
        <command>torquebox run</command> (Windows users remember to
        use <command>echo Y | jruby -S torquebox run</command>),
        navigate to <ulink url="http://localhost:8080/posts/"/>,
        create a new post, and observe the output from the TorqueBox
        console.

        <screen>09:11:19,746 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) Publishing 'Chunky Bacon Fever' to our favorite social network
09:11:24,747 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) Post published</screen>

        As you can see, it took 5 seconds to publish the post and
        during that five seconds the browser was waiting on a response
        from the server. There's no reason the browser needs to wait
        until the post is published, so let's see how easy it is to
        convert the publish_to_social_network method to run in the
        background.

        <example>
          <title><filename>~/torquebox_examples/rails_example/app/models/post.rb</filename></title>
          <programlisting><![CDATA[class Post < ActiveRecord::Base
  attr_accessible :body, :title

  after_create :publish_to_social_network
  always_background :publish_to_social_network

  def publish_to_social_network
    puts "Publishing '#{title}' to our favorite social network"
    sleep(5)
    puts "Post published"
  end
end]]></programlisting>
        </example>

        Create a new post and you'll see that the browser returns
        immediately and in the TorqueBox console the messaging runtime
        will spin up (since
        <classname>TorqueBox::Backgroundable</classname> uses
        messaging and the first message we send starts the messaging
        runtime pool) and publish the post to our favorite social
        network in the background.
      </para>
    </section>

    <section id="features-scheduled-jobs">
      <title>Scheduled Jobs</title>

      <para>
        TorqueBox also has built-in support for scheduled jobs (like
        Cron or Windows Scheduler) but in a cross-platform way. To see
        how scheduled jobs work, let's create a job that logs the
        number of posts in our database every 10 seconds. To do this
        create a <classname>PostCounter</classname> class in the
        <filename>app/jobs</filename> directory created for us by the
        TorqueBox Rails template earlier.

        <example>
          <title><filename>~/torquebox_examples/rails_example/app/jobs/post_counter.rb</filename></title>
          <programlisting><![CDATA[class PostCounter

  def run
    puts "#{Post.count} posts in the database"
  end

end]]></programlisting>
        </example>

        We also have to tell TorqueBox about this new job and when to
        run it. To do that, edit the
        <filename>config/torquebox.yml</filename> created for us by
        the TorqueBox Rails template to have the contents below.

        <example>
          <title><filename>~/torquebox_examples/rails_example/app/config/torquebox.yml</filename></title>
          <programlisting>---
# This is the TorqueBox configuration file. Refer to the TorqueBox
# documentation at http://torquebox.org/documentation/current/ 
# for all configuration options.
web:
  context: "/"
jobs:
  post_counter:
    job: PostCounter
    cron: "*/10 * * * * ?"</programlisting>
        </example>

        Since we had to make a change to
        <filename>config/torquebox.yml</filename>, we need to restart
        TorqueBox for the job to start running. After restarting
        TorqueBox you should see output like below every 10 seconds.

        <screen>09:45:30,029 INFO  [stdout] (JobScheduler$rails_example-knob.yml_Worker-2) 2 posts in the database</screen>
      </para>
    </section>

    <section id="features-services">
      <title>Long-Running Services</title>

      <para>
        TorqueBox supports the notion of long-running services that
        get started when the application is deployed and stopped when
        the application is undeployed. This could be useful to connect
        a client to a streaming API service (like that provided by
        some social networks), monitor a resource for changes and take
        some action, or many other things. As an example, we'll create
        a service that pretends to connect to a social network and
        submit post ideas to a queue for later processing.

        <example>
          <title><filename>~/torquebox_examples/rails_example/app/services/post_idea_grabber.rb</filename></title>
          <programlisting><![CDATA[class PostIdeaGrabber

  def initialize(options)
    @queue = TorqueBox::Messaging::Queue.new(options['queue_name'])
  end

  def start
    puts "******** Starting PostIdeaGrabber ********"
    Thread.new do
      until @done
        @queue.publish("Random idea #{rand(100)}")
        sleep 2
      end
    end
  end

  def stop
    @done = true
  end
end]]></programlisting>
        </example>

        Just like with our scheduled job, we need to tell TorqueBox
        about this new service and the message queue it uses.

        <example>
          <title><filename>~/torquebox_examples/rails_example/app/config/torquebox.yml</filename></title>
          <programlisting>---
# This is the TorqueBox configuration file. Refer to the TorqueBox
# documentation at http://torquebox.org/documentation/current/ 
# for all configuration options.
web:
  context: "/"
jobs:
  post_counter:
    job: PostCounter
    cron: "*/10 * * * * ?"
services:
  post_idea_grabber:
    service: PostIdeaGrabber
    config:
      queue_name: "/queue/post_ideas"
queues:
  /queue/post_ideas:
    durable: false</programlisting>
        </example>

        Restart TorqueBox and you should see the service starting in
        the logs.

        <screen>10:43:56,316 INFO  [org.torquebox.core.runtime] (MSC service thread 1-7) Created ruby runtime (ruby_version: RUBY1_8, compile_mode: JIT, app: rails_example, context: services) in 17.73s
10:43:56,325 INFO  [stdout] (MSC service thread 1-5) ******** Starting PostIdeaGrabber ********</screen>
      </para>
    </section>

    <section id="features-processors">
      <title>Message Processors</title>

      <para>
        We have a long-running service placing messages on a queue but
        now we need something to consume those messages and do
        something with them. TorqueBox has a feature designed
        specifically for this purpose - message processors. We'll
        create a message processor to randomly choose some of the
        ideas and create new posts from them.

        <example>
          <title><filename>~/torquebox_examples/rails_example/app/processors/post_idea_processor.rb</filename></title>
          <programlisting><![CDATA[class PostIdeaProcessor < TorqueBox::Messaging::MessageProcessor

  def on_message(message)
    if (rand(10) > 8)
      puts "Creating new post from idea #{message}"
      Post.create(:title => message, :body => "Random post created from an idea")
    end
  end

end]]></programlisting>
        </example>

        As usual we need to edit
        <filename>config/torquebox.yml</filename> so TorqueBox knows
        how to wire up this new message processor.

        <example>
          <title><filename>~/torquebox_examples/rails_example/app/config/torquebox.yml</filename></title>
          <programlisting>---
# This is the TorqueBox configuration file. Refer to the TorqueBox
# documentation at http://torquebox.org/documentation/current/ 
# for all configuration options.
web:
  context: "/"
jobs:
  post_counter:
    job: PostCounter
    cron: "*/10 * * * * ?"
services:
  post_idea_grabber:
    service: PostIdeaGrabber
    config:
      queue_name: "/queue/post_ideas"
queues:
  /queue/post_ideas:
    durable: false
messaging:
  /queue/post_ideas: PostIdeaProcessor</programlisting>
        </example>

        Restart TorqueBox and you should see new posts being created
        from the random ideas.

        <screen>11:10:31,891 INFO  [stdout] (Thread-2 (HornetQ-client-global-threads-9512807)) Creating new post from idea Random idea 66</screen>
      </para>

      <para>
        Congratulations! You now have an application that uses many of
        the features of TorqueBox. For detailed documentation on
        TorqueBox, look for the User Manual in the same location you
        found this Getting Started Guide.
      </para>
    </section>
  </chapter>

</book>
