<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
   <channel>
      <title>arc90 blog : Quick Tips</title>
      <link>http://blog.arc90.com/</link>
      <description>Arc90 is a Web 2.0 design consultancy that delivers next-generation technology solutions for our clients. With technologies like Ajax, Flash and RSS we deliver richer, more powerful strategies and end-user experiences. The arc90 blog is a place where we share our philosophy, ideas, experiences and thoughts on technology and business.</description>
      <language>en</language>
      <copyright>Copyright 2009</copyright>
      <lastBuildDate>Sat, 20 Jun 2009 18:56:18 -0500</lastBuildDate>
      <generator>http://www.sixapart.com/movabletype/?v=4.1</generator>
      <docs>http://blogs.law.harvard.edu/tech/rss</docs> 

      
      <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/arc90quickTips" type="application/rss+xml" /><feedburner:browserFriendly></feedburner:browserFriendly><item>
         <title> SQL Server Stored Procedure Introspection</title>
         <description><![CDATA[<p>Here at Arc90, a hallmark of our work is extremely dynamic, flexible systems.  In the process of building one of our platforms, I found myself calling some ever-evolving stored procedures with large numbers of parameters.  Hard coding these calls became tedious, buggy, and generally maddening.  I really needed to be able to dynamically discover all the pertinent info about the parameters for each sproc, and then spin up the call on the fly.  As part of the solution, I created a sproc that brings back a recordset of all input and output parameters and metadata for each.  Basically this sproc looks into the system tables and extracts all of the needed info.</p>

<p>This turns out to be particularly useful if you have large sets of data in which the names can be dynamically mapped to the param names.  It's suddenly a concise and simple matter to dynamically make large sproc calls.This procedure is simply called by passing in the name of the sproc that you want to examine.  The sproc code is commented with an explanation of each return field.</p>

<p>This is compatible with Sql Server 2005 and 2008.</p>

<p>Example call:</p>
<pre>
EXEC    spStoredProcParamLookup @ipSprocName = 'spTestSproc'
</pre>
<span class="mt-enclosure mt-enclosure-image" style="display: inline;"><img alt="sql.png" src="http://blog.arc90.com/sql.png" width="635" height="45" class="mt-image-left" style="float: left; margin: 0 20px 20px 0;" /></span>

<textarea name="code" class="sql">


/************************************************************************************
Software License Agreement (BSD License)

Copyright (c) 2008, Arc90 Inc.
All rights reserved.

Redistribution and use of this software in source and binary forms, with or
without modification, are permitted provided that the following conditions
are met:

- Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

- Neither the name of Arc90 Inc. nor the names of its contributors may be
  used to endorse or promote products derived from this software without
  specific prior written permission of Arc90 Inc.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************/

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE spStoredProcParamLookup
	-- The name of the sproc for which the params are being found
	@ipSprocName    VARCHAR(100)
	AS

	-- ======================================================
	-- Make sure there is a valid value for the sproc name
	-- ======================================================

	-- Check for blank or null
	IF @ipSprocName IS NULL OR @ipSprocName = ''
		BEGIN
			RAISERROR ('There must be a valid (non-empty and non-null) value for the param @ipSprocName',10,1)
		END

	-- Trim off extra spaces when user is typing information
	SELECT    @ipSprocName = LTRIM(RTRIM(@ipSprocName))


	-- ======================================================
	-- Get the data
	-- ======================================================

	SELECT		-- Name of the parameter. Is unique within the object. (includes preceding @)
				-- Datatype: sysname
				sp.name AS ParamName,

				-- ID of the parameter. Is unique within the object.
				-- Datatype: int
				sp.parameter_id AS ParamID,

				-- Maximum length of the parameter, in bytes.
				-- Value = -1 when the column data type is varchar(max), nvarchar(max), varbinary(max), or xml.
				-- Datatype: smallint
				sp.max_length AS MaxLength,

				-- A restatement of the original sproc name (same as value of @ipSprocName)
				-- This is just a convenience
				-- Datatype: sysname
				so.name AS ProcName,

				-- A string denoting the name of the datatype of the param (ie. Varchar)
				-- Datatype: sysname
				st.name AS DataTypeName,

				-- An int denoting the datatype of the param.  Sql Server assigns each datatype a unique int id.
				-- The full list of these types can be found in the table systypes.
				-- Datatype: tinyint
				st.type AS DataTypeID,

				-- Precision of the parameter if numeric-based; otherwise, 0.
				-- Datatype: tinyint
				sp.precision AS ParamPrecision,

				-- This denotes whether or not this is an output param
				-- 1 = an output param / 0 = input param
				-- Datatype: bit
				sp.is_output AS IsOutput,   

				-- This denotes where or not there is a default value set for this param. 
				-- 1 = Parameter has default value / 0 = does not
				-- This implicitly tells whether or not the param is required. A param with a
				-- default value specified is not required.
				-- Datatype: bit
				sp.has_default_value AS HasDefaultValue  

	FROM		sys.objects so
	INNER JOIN	sys.parameters sp ON (so.object_id = sp.object_id)
	INNER JOIN	sys.syscolumns sc ON so.object_id = sc.id
	INNER JOIN	sys.systypes st ON st.xusertype = sc.xusertype

	WHERE		sc.colid = sp.parameter_id
	AND			so.name = @ipSprocName

	ORDER BY	sp.parameter_id

GO
</textarea>
]]></description>
         <link>http://blog.arc90.com/2009/02/sql_server_stored_procedure_in.php</link>
         <guid>http://blog.arc90.com/2009/02/sql_server_stored_procedure_in.php</guid>
         <category>Quick Tips</category>
         <author>michaelh@arc90.com (Michael Helmuth)</author>
         <pubDate>Thu, 12 Feb 2009 14:35:01 -0500</pubDate>
      </item>
      
      <item>
         <title>Regexing to extract HTTP status codes</title>
         <description><![CDATA[<p>Today I was trying to figure out why a library I called was throwing unhandled exceptions when it called a REST web service that was (correctly) returning 401 Unauthorized. It turns out that the library, which does nothing but handle HTTP requests, throws WebExceptions, not the HttpExceptions I expected. All I had to go on was the exception message text <em>The remote server returned an error: (401) Unauthorized.</em></p>

<p>Since HttpException exposes a GetHttpCode() method and WebException does not, the HTTP status code from the underlying service was being discarded by this library, which made it impossible for me to automate error handling by status code. The <em>right</em> way to solve this problem is to fix the library to throw HttpExceptions to preserve status codes. But the <em>right now</em> way was to use regular expressions to see when these exception messages contained a three-digit number starting with 4 or 5 (e.g. 401, 404, 500) and wrap it in my own HttpException so that the caller further up the chain can process it automatically.</p>

<p>Note that an exception message like <em>404 is not a valid credit card number</em> would get erroneously treated as a 404 File Not Found exception. However, in this case where I know the library and the service involved I think it's safe to do. But I'm still going to fix the offending code ASAP! 

</p><pre name="code" class="C#">    // C#
    try
    {
        // call the library that might throw the exception 
        // that ought to be an HttpException
    }
    catch(System.Web.HttpException) // it's already an HttpException, so throw it as-is
    {
        throw; 
    }
    catch(Exception ex) // any other exception
    {
        // If the exception message contains a 3-digit number starting
        // with 4 or 5, assume it's the correct HTTP status code. 
        // NOTE! Know your library to know if that's a safe assumption!
        Regex httpErrorRegex = new Regex("((4|5)\\d{2})(?!\\d)");
        if(httpErrorRegex.IsMatch(ex.Message))
        {
            int httpStatusCode = int.Parse(httpErrorRegex.Match(ex.Message)
                .Captures[0].Value);
            throw new HttpException(httpStatusCode, ex.Message, ex);
        }

        // No 3-digit HTTP error code found in the message, so default to a 500 error
        throw new HttpException(500, ex.Message, ex);
    }
</pre>]]></description>
         <link>http://blog.arc90.com/2009/02/regex_to_demangle_http_excepti.php</link>
         <guid>http://blog.arc90.com/2009/02/regex_to_demangle_http_excepti.php</guid>
         <category>Quick Tips</category>
         <author>joelp@arc90.com (Joel Potischman)</author>
         <pubDate>Wed, 04 Feb 2009 14:24:51 -0500</pubDate>
      </item>
      
      <item>
         <title>Trac Bookmarklet</title>
         <description><![CDATA[<p>Already know your <a href="http://trac.edgewall.org/" target="_blank">Trac</a> ticket number and don't want to type a URL, scroll through your browser history, or have to search your Trac tickets? Customize <em>server</em> and <em>path</em> and save this bookmarklet for any Trac you use regularly:</p>

<p><input name="code" class="javascript" style="width: 100%;" value="javascript:void(location.href=('http://server/path/ticket/'+prompt('Enter%20ticket%20number')))" onfocus="this.select()" type="text" /></p>

<p>
If you save the bookmarklet to your browser's toolbar you simply click once, enter the ticket number, and you're in your ticket.</p>]]></description>
         <link>http://blog.arc90.com/2009/01/trac_bookmarklet.php</link>
         <guid>http://blog.arc90.com/2009/01/trac_bookmarklet.php</guid>
         <category>Quick Tips</category>
         <author>joelp@arc90.com (Joel Potischman)</author>
         <pubDate>Tue, 27 Jan 2009 14:26:12 -0500</pubDate>
      </item>
      
      <item>
         <title>Encoding and XML</title>
         <description><![CDATA[<p>In speccing a project last month, we discussed the best way to attach PDFs to the XML documents we send between very distributed systems. We <a href="http://blog.arc90.com/2008/12/groovy_and_python_for_quick_sc.php" target="_blank">quickly</a> decided it would avoid a whole host of atomicity, reliability, and redesign issues to simply update our XML schema to include Base64 encoded documents inside the body of the XML document itself.</p>

<p>For my half of our application ecosystem I researched .NET's Base64 encoding/decoding support, got curious about character set encoding, and set out to write a universal encoder to make it simple, easy, and guaranteed safe to insert any kind of binary or text data into an XML document.</p>

<p>But first, a quick nano-refresher: <a href="http://en.wikipedia.org/wiki/Character_encoding" target="_blank">Character encoding</a> specifies how a string of bytes should be mapped to specific text characters. In the simplest case, ASCII, one byte maps to one of 256 possible characters. 65=A, 66=B, .... 90=Z, etc. In <a href="http://en.wikipedia.org/wiki/Unicode" target="_blank">Unicode</a>, two (or even four) bytes map to thousands or even (theoretically) billions of characters. So when my program reads four bytes from a text file, I need to know if it represents four 1-byte characters, two 2-byte characters, or one 4-byte character. It's actually <a href="http://en.wikipedia.org/wiki/Endianness" target="_blank">even</a> <a href="http://en.wikipedia.org/wiki/Character_encoding" target="_blank">more</a> <a href="http://en.wikipedia.org/wiki/Byte_order_mark" target="_blank">complicated</a> than that, but the basic problem is making sure I don't accidentally turn a 400-byte ASCII text file into 200 Japanese characters. Or vice versa. Or garbage.</p>

<p>Fortunately, .NET has robust support for character encoding, so all I have to do is load the correct encoding class and ask it to take care of this for me. If I know I will only ever need to deal with Unicode, that class is <strong>Encoding.Unicode</strong>, but for maximum flexibility I can call <strong>Encoding.GetEncoding(encodingName)</strong> and get any encoding by name. Like so:</p>

<pre name="code" class="c#">
public string GetStringFromFile(string myFilename, string encodingName)
{
    byte[] fileBytes = System.IO.File.ReadAllBytes(myFilename);
    System.Text.Encoding myEncoding = System.Text.Encoding.GetEncoding(encodingName);
    return myEncoding.GetString(fileBytes);
}
</pre>

After I'm done modifying that string I can easily convert it back into a byte array and save it, preserving the original character encoding:

<pre name="code" class="c#">
public void SaveStringToFile(string myFilename, string encodingName, string myString)
{
    System.Text.Encoding myEncoding = System.Text.Encoding.GetEncoding(encodingName);
    byte[] fileBytes = myEncoding.GetBytes(myString);
    System.IO.File.WriteAllBytes(myFilename, fileBytes);
}
</pre>

<p>But now let's get back to my actual business problem, storing a PDF or other binary data in my XML document. Because the bytes I encounter are not supposed to represent character data, attempting to map them to characters may result in nonsense. For example, whether I decode the byte sequence <strong>00 00 00 00</strong> as ASCII, Unicode, or UTF-32, I get either one, two, or four <a href="http://en.wikipedia.org/wiki/Null_character" target="_blank">null characters</a> that will screw up string processing. Note that use of CDATA sections doesn't help. Only being very lucky about which byte sequences I encounter would avert disaster, and I don't like writing lucky code.</p>

<p>Enter <a href="http://en.wikipedia.org/wiki/Base64" target="_blank">Base64</a>, which is designed for exactly this purpose: encoding arbitrary binary data into a string guaranteed to consist of only "safe" ASCII characters and decoding that string back to bytes with 100% fidelity later. Microsoft places Base64 functionality under the <strong>System.Convert</strong> class, not <strong>System.Text.Encoding</strong> because it's more of a conversion and translation process, not a direct byte-to-character encoding like those described above.</p>

<p>To read a file into a Base64 string:</p>

<pre name="code" class="c#">
public string GetBase64StringFromFile(string myFilename)
{
    byte[] fileBytes = System.IO.File.ReadAllBytes(myFilename);
    return Convert.ToBase64String(fileBytes, Base64FormattingOptions.InsertLineBreaks);
}
</pre>

<p>And to decode it and save it back to the filesystem:</p>

<pre name="code" class="c#">
public void SaveBase64StringToFile(string myFilename, string myString)
{
    byte[] fileBytes = Convert.FromBase64String(myString);
    System.IO.File.WriteAllBytes(myFilename, fileBytes);
}
</pre>

<p>I combined both "real" character encodings and Base64 encoding in my XmlFileEncoder class (attached) to provide unified access to both encodings when working with XML documents. If you know you're dealing with Unicode, simply call <strong>XmlFileEncoder.InsertFileIntoXmlDocument</strong> with the encoding <em>UTF-16</em> and the file will safely be inserted as text. If you don't always know the file format, or you are dealing with binary files, simply call the same method with the encoding <em>Base64</em>. In either case, a new node will be added to contain your file data and the <em>encoding</em> attribute will record the encoding method so <strong>XmlFileEncoder.ExtractFileFromXmlDocument</strong> will use the correct character/Base64 decoding automatically.</p>

<p>The demo WinForms app starts up displaying an XML document with some UTF-16 data already encoded into it. Use the controls along the bottom to experiment with inserting differently encoded files (provided, or use your own) using different application character encodings. Some files will clearly look wrong in the XML when you select the wrong encoding. Others may look correct, or almost correct, but when you press the SaveEncodedFile to File button it will report Copy accuracy FAILED when it verifies against the source file. However, the files encoded and decoded using Base64 will <u>always</u> copy accurately. The only downside is that Base64 encoded data is always 1/3 bigger and much less human readable than the source.</p>

<p>You can find the source code here: <span class="mt-enclosure mt-enclosure-file" style="display: inline;"><a href="http://blog.arc90.com/XmlEncodingDemo.zip">XmlEncodingDemo.zip</a></span>

<p>Have a happy, healthy, and correctly encoded 2009!</p>]]></description>
         <link>http://blog.arc90.com/2009/01/encoding_and_xml.php</link>
         <guid>http://blog.arc90.com/2009/01/encoding_and_xml.php</guid>
         <category>Quick Tips</category>
         <author>joelp@arc90.com (Joel Potischman)</author>
         <pubDate>Tue, 06 Jan 2009 14:22:56 -0500</pubDate>
      </item>
      
      <item>
         <title>Gotcha: Adding Metadata to a Flex Component</title>
         <description><![CDATA[<p>Recently, I noticed that as I was adding event metadata to my custom Flex components, Flex Builder wasn't giving me code hints for those configured events. For example, I would do the following:</p>

<pre>
[Event(name='complete', type='flash.events.Event')]
</pre>

<p>Since I wasn't seeing the event in the code hints list I looked at some inner Flex framework components like Button or TextInput to see what I was doing wrong. Everything matched but then I realized the only difference was that they used double quotes. Aha! Once I switched the above metadata example to the following, everything worked out:</p>

<pre>
[Event(name="complete", type="flash.events.Event")]
</pre>

<p>The complete event showed up in the code hints list when trying to add an event listener for my custom component. This isn't a complaint on Flex Builder, as I normally  use double quotes--so I blame this on laziness and copying and pasting the metadata line but to others be careful and note to see the event (or any other metadata type e.g. styles) show up in the code hints list always use double quotes!</p>]]></description>
         <link>http://blog.arc90.com/2008/12/gotcha_adding_metadata_to_a_fl.php</link>
         <guid>http://blog.arc90.com/2008/12/gotcha_adding_metadata_to_a_fl.php</guid>
         <category>Quick Tips</category>
         <author>javierj@arc90.com (Javier Julio)</author>
         <pubDate>Mon, 08 Dec 2008 16:30:27 -0500</pubDate>
      </item>
      
      <item>
         <title>Java Quick Tip: Parameterized Logging</title>
         <description><![CDATA[<p>I hate writing ugly, concatenated logging statements like this:</p>

<pre name="code" class="php">
package com.arc90.example;

import java.util.logging.Logger;

public class LoggingExample1
{
	public static void main(String[] args)
	{
		Logger logger = Logger.getLogger(LoggingExample1.class.getName());
		
		String user = "dougb";
		int logins = 17;
		int purchases = 2;
		
		logger.info("User " + user + " has logged in " + logins + 
				" times and made " + purchases + " purchases.");
	}
}
</pre>

<p>Fortunately, the Java Logging API gives you the ability to parameterize your statements (similar to JDBC prepared statements) so that you can turn the above into something like this:</p>

<pre name="code" class="php">
package com.arc90.example;

import java.util.logging.Level;
import java.util.logging.Logger;

public class LoggingExample2
{
	public static void main(String[] args)
	{
Logger logger = Logger.getLogger(LoggingExample2.class.getName());
		
		String user = "dougb";
		int logins = 17;
		int purchases = 2;

		// Single parameter
		logger.log(Level.INFO, "User {0} successfully logged in.", user);
		
		// Multiple parameters
		logger.log(Level.INFO, "User {0} has logged in {1} times and made {2} purchases.", 
				new Object[] {user, logins, purchases});
	}
}
</pre>

<p>
You'll need to use the logger.log(...) method rather than the more convenient logger.fine(...), logger.info(...) (etc.) methods, but in the end it makes for much cleaner code.
</p>]]></description>
         <link>http://blog.arc90.com/2008/12/java_quick_tip_parameterized_l.php</link>
         <guid>http://blog.arc90.com/2008/12/java_quick_tip_parameterized_l.php</guid>
         <category>Quick Tips</category>
         <author>dougb@arc90.com (Doug Burns)</author>
         <pubDate>Tue, 02 Dec 2008 13:50:10 -0500</pubDate>
      </item>
      
      <item>
         <title>Enabling SSL on Windows with PHP and the Zend Framework</title>
         <description><![CDATA[<p>Ever tried to use HTTPS with PHP and the Zend Framework on Windows, but only received an error for all your troubles? Perhaps an error like: </p>

<pre>
    Unable to Connect to ssl://( your host name):443.
    Error #175113224: Unable to find the socket transport "ssl" - 
    did you forget to enable it when you configured PHP?</pre>

<p>The problem lies in your version of OpenSSL and certain configuration parameters.</p>

<p>HTTPS relies on SSL to transport your data securely and PHP usually uses the OpenSSL implementation of SSL. Problems occur when your versions of OpenSSL are out of sync with each other.</p>

<p>The best option is to always keep ALL of your software 100% up-to-date at all times--but sometimes you are not able to do a full software update for one reason or another.</p><p>This is how to ensure OpenSSL works for you:</p>

<p>There are 4 required files for openSSL: libeay32.dll, ssleay32.dll, php_openssl.dll, and openssl.cnf.</p>

<p>libeay32.dll and ssleay32.dll are usually already installed in multiple places, but are usually in different versions. The safest thing to do is rename all the current files and copy in a known version. Make sure you have the most current version by installing the most current version from this site: <a href="http://www.slproweb.com/products/Win32OpenSSL.html" target="_blank">Shining Light Productions</a></p>

<p>It is probably best to do a search for these files to see all the locations, but they usually live in the following places on a 64-Bit server:</p>
<pre>
     C:\Program Files (x86)\PHP
     C:\Program Files (x86)\Apache Group\Apache2\bin
     C:\Windows\SysWOW64
</pre>

<p>Go to all of these places and rename the files libeay32-old.dll and ssleay32-old.dll, respectively, then copy libeay32.dll and ssleay32.dll to those locations.</p>

<p>If it doesn't already exist, copy php_openssl.dll to:</p>
<pre>
     C:\Program Files (x86)\PHP\ext </p></pre>
<p>If you do not have php_openssl.dll, one place to find it is <a href="http://www.dlldll.com/php_openssl.dll_download.htm" target="_blank">here.</a></p>

<p>If it doesn't already exist, copy openssl.cnf to:</p>
<pre>
     C:\Program Files (x86)\PHP\extra\openssl</pre>
<p>Create directories if they do not already exist. If you do not have openssl.cnf, you can download PHP's default cnf file <a href="http://arc90.com/temp/openssl.cnf" target="_blank">here.</a></p>
 
<p>Add the following line to php.ini:</p>
<pre>
     extension=php_openssl.dll</pre>

<p>Make sure the following line is uncommented in httpd.conf:</p>
<pre>
     LoadModule ssl_module modules/mod_ssl.so</pre>

<p>Restart Apache.</p>


<p>You're done!</p>]]></description>
         <link>http://blog.arc90.com/2008/11/_ever_try_to_use.php</link>
         <guid>http://blog.arc90.com/2008/11/_ever_try_to_use.php</guid>
         <category>Quick Tips</category>
         <author>michaelr@arc90.com (Michael Rehse)</author>
         <pubDate>Tue, 11 Nov 2008 14:15:00 -0500</pubDate>
      </item>
      
      <item>
         <title>Ignore Double Slashes in URLs in Restlet Applications</title>
         <description><![CDATA[<p>Every once in a while, people accidentally type two slashes instead of
one in their URLs.</p>

<p>The Apache httpd server will automatically ignore the double slashes,
and treat the URL as if the double slash was a single slash. This is
helpful; the server is giving the user what they want, even though
they technically didn't ask for it correctly.</p>

<p>Reslet's Router class, however, isn't so forgiving. If you
accidentally include a double-slash in the URL of a request, a Restlet
application will probably return a 404 Not Found status code.<p>

<p>Thankfully, Restlet's request handling process is so flexible, we can
easily add a Filter which will cause the application to ignore double
slashes, just like httpd.</p>

<p>If your application uses a subclass of Restlet's Application class,
then it is overriding the default <code>getRoot()</code> method to
provide your own request handling Restlets.</p>

<p>A standard <code>getRoot()</code> might look something like this:<p>

<pre class="code java">
@Override
public Restlet getRoot()
{
       Router router = new Router();

       // Attach all the routes
       router.attach("path", ResourceClass.class);

       return router;
}
</pre>

<p>In order to remove double slashes from request URLs before they reach
the router, we can create an anonymous Filter class and return it as
the root of the application:<p>

<pre class="code java">
@Override
public Restlet getRoot()
{
       Filter doubleSlashFilter = new Filter() {
               @Override
               protected int beforeHandle(Request request, Response response) {
                       Reference ref = request.getResourceRef();

                       String originalPath = ref.getPath();

                       if (originalPath.contains("//"))
                       {
                               String newPath = originalPath.replaceAll("//", "/");
                               ref.setPath(newPath);
                       }

                       return Filter.CONTINUE;
               }
       };

       Router router = new Router();

       // Attach all the routes
       router.attach("path", ResourceClass.class);

       doubleSlashFilter.setNext(router);

       return doubleSlashFilter;
}
</pre>

<p>And that's it! The application will now ignore double slashes, and
will successfully serve requests that accidentally include them.</p>]]></description>
         <link>http://blog.arc90.com/2008/11/ignore_double_slashes_in_urls.php</link>
         <guid>http://blog.arc90.com/2008/11/ignore_double_slashes_in_urls.php</guid>
         <category>Quick Tips</category>
         <author>avif@arc90.com (Avi Flax)</author>
         <pubDate>Wed, 05 Nov 2008 17:00:00 -0500</pubDate>
      </item>
      
      <item>
         <title>Instant Web Sharing via Python</title>
         <description><![CDATA[<p>This is a <a href="http://www.reddit.com/r/linux/comments/76p14/woof_simply_exchange_files/c05tpub">neat trick I saw from 'mrlawlsome' on reddit</a> and didn't want to pass up.</p><p>Ever been on an internal network and wanted to share a file or two quickly? This little *nix script will let you do so in a snap. (And it works on Mac OS X, too!)</p><p>From the command line, just type:<br /></p>

<pre><code>python -c "import SimpleHTTPServer;SimpleHTTPServer.test()"</code></pre>While
running, this python script will run a simple web server with your
current working directory as the root. Just browse to
http://[youripaddress]:8000 to see it in action!<br /><br />This script is probably most useful as an alias. Just add the following into your .bashrc file:<br /><pre><code>alias webshare='python -c "import SimpleHTTPServer;SimpleHTTPServer.test()"'<br /></code></pre>You can now just use 'webshare' whenever you want to allow access to some files on your machine. Pretty slick!]]></description>
         <link>http://blog.arc90.com/2008/10/instant_web_sharing_via_python.php</link>
         <guid>http://blog.arc90.com/2008/10/instant_web_sharing_via_python.php</guid>
         <category>Quick Tips</category>
         <author>chrisd@arc90.com (Chris Dary)</author>
         <pubDate>Mon, 27 Oct 2008 16:32:28 -0500</pubDate>
      </item>
      
      <item>
         <title>Removing Padding Between a Flex List and Its Item Renderers</title>
         <description><![CDATA[<p>While working on an AIR client, I had a design comp that required a line divider below each item renderer in a Flex List component. The List component has a style for alternating item colors but not for adding a line divider between each item renderer. I figured it shouldn't be that hard because I can simply add a bottom border on the container used for the item renderer.</p><p>I'm using a Canvas so the top portion of my MXML item renderer looked like:</p>

<textarea name="code" class="js">

<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" 
borderColor="#dedede" borderSides="bottom" borderStyle="solid">
...
</mx:Canvas>

</textarea>

<p>Easy, but not quite there. You see the Flex List component seems to add some default spacing around the left and bottom parts of each item renderer from the List edge. You can see this in the following screenshot (I've changed the colors so the edges stand out):</p>

<span class="mt-enclosure mt-enclosure-image" style="display: inline;"><img alt="javisimage1.png" src="http://blog.arc90.com/javisimage1.png" width="78" height="130" class="mt-image-center" style="text-align: center; display: block; margin: 0 auto 20px;" /></span>

<p>As you can see, there is whitespace between the left edge and the starting point of the border and our selection highlight seems to be out of place. This is undesirable but there is an easy fix. It seems the List component has some default left and bottom padding set, so simply override it with nothing. Here I'm setting the rules globally to all List components, but you can replace it with the style name for a specific one if needed:</p>

<textarea name="code" class="js">
List {
  padding-bottom: 0;
  padding-left: 0;
}
</textarea>

<p>After applying that snippet of CSS, we now have an item renderer where the selection highlight is in line with the left edge of the List and the next item. You can see the result below:</p>

<span class="mt-enclosure mt-enclosure-image" style="display: inline;"><img alt="javisimage2.png" src="http://blog.arc90.com/javisimage2.png" width="78" height="156" class="mt-image-center" style="text-align: center; display: block; margin: 0 auto 20px;" /></span>]]></description>
         <link>http://blog.arc90.com/2008/10/removing_padding_between_a_fle.php</link>
         <guid>http://blog.arc90.com/2008/10/removing_padding_between_a_fle.php</guid>
         <category>Quick Tips</category>
         <author>javierj@arc90.com (Javier Julio)</author>
         <pubDate>Wed, 01 Oct 2008 14:14:21 -0500</pubDate>
      </item>
      
      <item>
         <title>Marking Up Forms</title>
         <description><![CDATA[<p>Here is my approach when creating forms:</p>

<ul class="blog_list">
<li>
Make use of the label/input value pair tags. Have the label <strong>for</strong> the attribute equal its corresponding input's <strong>id</strong>. This allows the user to activate its control by clicking on the text. Example below:
<pre name="code" class="html">
&lt;label for=&quot;fn&quot;&gt;First Name&lt;/label&gt;
&lt;input type=&quot;text&quot; id=&quot;fn&quot; class=&quot;text_input&quot;&gt;
</pre>
</li>

<li>
<p>Give each <strong>input type="text"</strong> a class.</p>


<p>IE6 does not recognize attribute selectors. So, if you style the input selector (ie. input { border: 1px solid #CCC; }), and the form contains radio buttons or checkboxes, IE6 will apply that particular style to all inputs.</p>

<div class="align_c"><img src="http://arc90.com/_img/ie_screen.png" alt="IE6 Screenshot"></div>
</li>
<li>
<p>To adjust label width, float the label, then give it a width. Differentiate floating from from non-floating labels with &lt;p&gt;s and &lt;div&gt;s.</p>

Example:

<pre name="code" class="html">
&lt;style type=&quot;text/css&quot; media=&quot;screen&quot;&gt;
       #myform p label { float: left; width: 9em; }
&lt;/style&gt;
&lt;p&gt;
       &lt;label for=&quot;s_addrs&quot;&gt;Shipping Address&lt;/label&gt;
       &lt;input type=&quot;text&quot; name=&quot;some_form&quot; value=&quot;s_addrs&quot; id=&quot;s_addrs&quot; class=&quot;text_input&quot;&gt;
&lt;/p&gt;

&lt;div&gt;
       &lt;input type=&quot;checkbox&quot; value=&quot;&quot; id=&quot;check_saddrs&quot; class=&quot;text_input&quot;&gt;
       &lt;labe for=&quot;check_saddrs&quot;&gt;Check if shipping address is different from personal&lt;/labe&gt;
&lt;/div&gt;</pre>
</li>
 <li>
Make sure you are careful when using the universal reset rule - * { padding: 0; margin: 0; }. This affects browser form elements. Below is a screenshot differentiating the padding on the right side of a select tag when the reset rule is not-applied/applied on Firefox 2.
 
<div class="align_c"><img src="http://arc90.com/_img/ie_screen2.png" alt="IE6 Screenshot"></div>
</li>
</ul>
 
<p>I believe that these steps are a great starting point when creating forms. Good luck! </p>
]]></description>
         <link>http://blog.arc90.com/2008/09/marking_up_forms.php</link>
         <guid>http://blog.arc90.com/2008/09/marking_up_forms.php</guid>
         <category>Quick Tips</category>
         <author>alexg@arc90.com (Alex Gutierrez)</author>
         <pubDate>Mon, 29 Sep 2008 13:55:57 -0500</pubDate>
      </item>
      
      <item>
         <title>Java Quick Tip: Class.forName() with Java Generics</title>
         <description><![CDATA[<p>In most cases (Lists, Maps, etc.) the syntax for using Java Generics is pretty straight forward, but for Class.forName(...) that's not the case (at least for me).</p>

<p>
Here's an example of how it's done. The first code block is the pre-Generics way. It still works, but results in a compiler warning. The second block is the new Generics way that doesn't generate the warning.
</p><pre name="code" class="php">
package com.arc90.example;

/**
 * Demonstrates use of Class.forName(...) with Java Generics
 */
public class GenericsExample
{
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception
	{
		/*
		 * This gives the compiler warning:
		 * "Class is a raw type. References to generic type Class&lt;T&gt; should be parameterized"
		 */
		Class c1 = Class.forName("com.arc90.blog.InstantiateMe");
		ImplementMe i1 = (ImplementMe) c1.newInstance();
		System.out.println(i1.getClass().getName());
		
		/*
		 * This gives no compiler warning
		 */
		Class&lt;? extends ImplementMe&gt; c2 = Class.forName("com.arc90.blog.InstantiateMe").asSubclass(ImplementMe.class);
		ImplementMe i2 = c2.newInstance();
		System.out.println(i2.getClass().getName());
	}
}
</pre>
</pre>

<p>
To try this yourself you'll need to create two additional classes; An empty interface named <em>ImplementMe</em> and an empty class named <em>InstantiateMe</em> that implements <em>ImplementMe</em>.
</p>]]></description>
         <link>http://blog.arc90.com/2008/09/java_quick_tip_classforname_wi.php</link>
         <guid>http://blog.arc90.com/2008/09/java_quick_tip_classforname_wi.php</guid>
         <category>Quick Tips</category>
         <author>dougb@arc90.com (Doug Burns)</author>
         <pubDate>Wed, 24 Sep 2008 11:29:25 -0500</pubDate>
      </item>
      
      <item>
         <title>Extending Zend_Controller_Action More Productively</title>
         <description><![CDATA[<p>If you&#8217;re developing web apps using the Zend Framework, you&#8217;ll notice that your application-specific controller classes will need to share similar functionality with each other. For example, you may want to see if a user is logged in before granting him access to the actions of that controller, or maybe each controller needs a few objects instantiated before it can do its business. One way to do this would be to create a file and include it in the init function. This way you only write the code once, and you can include it in every class like so:</p>

<textarea name="code" class="xml">

public function init()
{
    require_once &#8216;sharedFunctions.php&#8217;;
}

</textarea>


<p>But that&#8217;s not really so elegant. It doesn&#8217;t really support any object-oriented design patterns. It&#8217;s ugly. So what is a better solution? Use inheritance! Your controller classes don&#8217;t have to directly extend Zend_Controller_Action. Instead, write a parent class for all of your controllers that extends Zend_Controller_Action.</p>

<p>
<span class="mt-enclosure mt-enclosure-image" style="display: inline;"><img alt="zend blog graph.jpg" src="http://blog.arc90.com/zend%20blog%20graph.jpg" width="599" height="370" class="mt-image-center" style="text-align: center; display: block; margin: 0 auto 20px;" /></span>
</p>

<p>Let&#8217;s move on with an example.  Say you&#8217;re writing an application that requires all actions to authenticate. If you only had one controller, you could put this check in public function init() and it would be executed before each action is called. But this application isn&#8217;t so basic. It&#8217;s pretty complex and your architecture requires you to have multiple controller classes. So, instead, create a new class called App_Controller_Action (or namespace it however you&#8217;d like). Put it in your include path, the same way you have the Zend Framework set up: App/Controller/Action.php (this way it will autoload the same way the Zend Framework classes load).</p>

<textarea name="code" class="xml">
class App_Controller_Action extends Zend_Controller_Action
{
    public function isAuthenticated()
    {
        ...
    }
    public function moreSharedFunctionality()
    {
        ...
    }
}
</textarea>

<p>Now all of your controller classes should be children of this class.</p>

<textarea name="code" class="xml">
class Users_Controller extends App_Controller_Action
{
    public function init()
    {
        if($this->isAuthenticated())
        {
            ...
        }

        $this->moreSharedFunctionality();
    }
}
</textarea>

<p>I&#8217;m sure you can find tons of other examples where this pattern can be useful in your applications. If you need any more help with this drop me a line at <a href="mailto:davidh@arc90.com">davidh@arc90.com</a>. If you have anything to add, comment below. Have fun coding! </p>]]></description>
         <link>http://blog.arc90.com/2008/09/extending_zend_controller_action.php</link>
         <guid>http://blog.arc90.com/2008/09/extending_zend_controller_action.php</guid>
         <category>Quick Tips</category>
         <author>davidh@arc90.com (Dave Hauenstein)</author>
         <pubDate>Mon, 22 Sep 2008 17:29:03 -0500</pubDate>
      </item>
      
      <item>
         <title>Configuring Restlet 1.1 with Spring</title>
         <description><![CDATA[<p>
Back in May I wrote a <a href="http://blog.arc90.com/2008/05/java_quick_tip_restlet_spring.php">post</a> about using Spring with Restlet 1.0.x and promised another about doing the same with Restlet 1.1.x, which provides better Spring support. Well, the time has come, so here goes!
</p>
<p>
In Restlet 1.1, which is currently at Release Candidate 1, you can now configure an application completely within the Spring application context. This means that the only Java classes you will need to create are one for starting the application, and one for each of the resources in your class. Although the Restlet authors prefer specifying the configuration in code, I like specifying it in an external, non-compiled configuration file, and this provides a great way to do that.
</p><p>
Now on to the code! A single-resource application can be configured with only three files: One XML file for defining the Spring beans, one class for defining the resource, and finally, one class for instantiating the Spring context and starting the application.
</p>

<h3>Spring Application Context</h3>
<p>
This defines all the Spring beans (Java Object instances) that are needed to run the application. In a non-Spring configured
application these would all be instantiated in your main application class.
<ul>
<li>exampleResource: A standard Resource. In a normal application you would define many resources in the <em>attachments</em> map.</li>
<li>restletRouter: Determines how resource URLs map to resource classes.</li>
<li>exampleApplication: Associates the router with an application.</li>
<li>restletServer: Defines the protocol and HTTP port for the internal server.</li>
<li>restletComponent: Associates the server and application. This is the object that will be used to start the server.</li>
</ul>
</p>

<pre name="code" class="xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xmlns:util=&quot;http://www.springframework.org/schema/util&quot;
    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd&quot;&gt;

    &lt;bean name=&quot;exampleResource&quot;
        class=&quot;com.arc90.example.ExampleResource&quot; scope=&quot;prototype&quot; /&gt;
   
    &lt;bean name=&quot;restletRouter&quot;
        class=&quot;org.restlet.ext.spring.SpringRouter&quot;&gt;
        &lt;property name=&quot;attachments&quot;&gt;
            &lt;map&gt;
                &lt;entry key=&quot;/example&quot;&gt;
                    &lt;bean class=&quot;org.restlet.ext.spring.SpringFinder&quot;&gt;
                        &lt;lookup-method name=&quot;createResource&quot; bean=&quot;exampleResource&quot;/&gt;
                    &lt;/bean&gt;
                &lt;/entry&gt;
            &lt;/map&gt;
        &lt;/property&gt;
    &lt;/bean&gt;
   
    &lt;bean id=&quot;exampleApplication&quot;
        class=&quot;org.restlet.Application&quot;&gt;
        &lt;property name=&quot;root&quot; ref=&quot;restletRouter&quot;/&gt;
    &lt;/bean&gt;
   
    &lt;bean id=&quot;restletServer&quot;
        class=&quot;org.restlet.ext.spring.SpringServer&quot;&gt;
        &lt;constructor-arg value=&quot;http&quot; /&gt;
        &lt;constructor-arg value=&quot;8182&quot; /&gt;
    &lt;/bean&gt;
   
    &lt;bean id=&quot;restletComponent&quot;
        class=&quot;org.restlet.ext.spring.SpringComponent&quot;&gt;
        &lt;property name=&quot;server&quot; ref=&quot;restletServer&quot; /&gt;
        &lt;property name=&quot;defaultTarget&quot; ref=&quot;exampleApplication&quot;/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</pre>

<h3>Resource Class</h3>
<p>
This is just a simple resource that displays &quot;It worked!&quot; when it is accessed through GET.
</p>
<pre name="code" class="php">
package com.arc90.example;

import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.ResourceException;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

/**
 * Handles requests for the example resource
 */
public class ExampleResource extends Resource
{
	public void init(Context context, Request request, Response response)
	{
		super.init(context, request, response);
		getVariants().add(new Variant(MediaType.TEXT_PLAIN));
	}

	public Representation represent(Variant variant) throws ResourceException
	{
		return new StringRepresentation(&quot;It worked!&quot;, MediaType.TEXT_PLAIN);
	}	
}
</pre>

<h3>Application Class</h3>
<p>
This class contains the main method for starting the application. It instantiates the Spring application context,
where creates instances for the beans defined in application-context.xml. To start the application, the component
bean is retrieved from the application context, then its start() method is called.
</p>
<pre name="code" class="php">
package com.arc90.example;

import org.restlet.ext.spring.SpringComponent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Launches the Restlet application
 */
public class ExampleApplication
{
	/**
	 * Get the restlet component from Spring, then starts it
	 * @param args
	 */
	public static void main(String[] args)
	{
		ApplicationContext context = 
			new ClassPathXmlApplicationContext(new String[] { &quot;application-context.xml&quot; });
		
		try
		{
			SpringComponent component = (SpringComponent) context.getBean(&quot;restletComponent&quot;);
			component.start();
		}
		catch (Exception e)
		{
			throw new RuntimeException(e);
		}
	}
}
</pre>]]></description>
         <link>http://blog.arc90.com/2008/09/configuring_restlet_11_with_sp.php</link>
         <guid>http://blog.arc90.com/2008/09/configuring_restlet_11_with_sp.php</guid>
         <category>Development</category>
         <author>dougb@arc90.com (Doug Burns)</author>
         <pubDate>Mon, 15 Sep 2008 12:56:59 -0500</pubDate>
      </item>
      
      <item>
         <title>Custom HTTP Response Headers with Restlet</title>
         <description><![CDATA[<p>Our Java apps use the <a href="http://restlet.org">Restlet</a> framework, and we sometimes need to send custom headers in our HTTP responses. This is infrequent enough that we forget how to do so, and need to look it up, but frequent enough that we should really have this snippet close at hand.</p>
<p>So here's how one adds a custom HTTP header to a Restlet Response:</p>

<pre name="code" class="java">
Form responseHeaders = (Form) getResponse().getAttributes().get("org.restlet.http.headers");

if (responseHeaders == null)
{
    responseHeaders = new Form();
    getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
}

responseHeaders.add("X-Some-Header", "the value");
</pre>]]></description>
         <link>http://blog.arc90.com/2008/09/custom_http_response_headers_w.php</link>
         <guid>http://blog.arc90.com/2008/09/custom_http_response_headers_w.php</guid>
         <category>Development</category>
         <author>avif@arc90.com (Avi Flax)</author>
         <pubDate>Mon, 15 Sep 2008 12:27:40 -0500</pubDate>
      </item>
      
   </channel>
</rss>
