Archive for the ‘Tools’ Category

JSDOM

Monday, November 22nd, 2010

Over the past few years, Javascript has matured from an "amateur’s programming language" into a full-fledged platform. Projects like Google Chrome and JQuery have helped elevate the language into a serious platform for delivering applications.

On the server side, projects like Google’s V8 show off Javascript’s prowess and power beyond the browser. Building on top of V8, Node.js leverages sever-side Javascript to allow for incredibly powerful, scalable software. Unfortunately, what isn’t included in the box with Node.js is the ability to leverage the powerful DOM capabilities built into nearly every browser that exists today. Enter our latest Arc90 Lab tool, JSDOM.

Jsdom is a CommonJS implementation of the W3C Document Object Model (DOM) designed to work with Node.js. It is intended to be platform independent and as minimal/light as possible while adhering to the W3C DOM specifications.


Why build this?

One of the first things that a front-end developer coming to a server-side Javascript platform notices is the lack of a window and/or document object.  Without a browser environment it is impossible to run the frameworks and libraries that we have all come to know and love.  JSDOM provides such a browser environment making it easy load external scripts and execute them in the context of a browser Window on the server.

By allowing both the server and the browser to interpret and manipulate the DOM, a host of new possibilities arise. For example, graceful degradation from rich AJAX-style experiences to simpler page-driven experiences is now much easier with JSDOM. In addition, powerful server-side DOM manipulation (e.g. to extract or replace certain elements depending on certain conditions) is now possible.

How does it work?

Getting started with JSDOM is quite simple. You will need node.js and the JSDOM library, and of course, a basic understanding of Javascript.

The following example shows how to create a DOM Window, load the jQuery framework, and run some code – right on the server:

    var html = '
    <html>\
      <head>\
      </head>\
        <body>\
        <h1>Hello World</h1>\
        <p>This is a <em>stupid simple</em> example</p>\
        </body>\
    </html>\
    ';

    // create a new window, with the above markup
    var window = require('jsdom').jsdom(html).createWindow(),

        // create a new script tag to load up jQuery
        script = window.document.createElement('script');

    script.src = 'http://code.jquery.com/jquery-1.4.2.js';

    // when jQuery finishes loading
    script.onload = function() {

      // Since this is not a browser we need to specify the window that jQuery has
      // been added to

      // Output: 'H1 Contents: Hello World'
      console.log("H1 Contents:", window.jQuery('h1').text());

      // do a simple replace on the `em` text above
      window.jQuery('p em').text('silly');

      // Output: 'P Contents: This is a silly example'
      console.log("P Contents:", window.jQuery('p').text());
    };

    // Append the element to the head element of the document
    window.document.head.appendChild(script);

Installation

JSDOM’s source code is hosted on github along with examples, use cases, and other useful information. You may also use NPM to install JSDOM by typing the following in your terminal `npm install jsdom`

License

This library is licensed under the MIT Open Source license.

Acknowledgement

This ambitious project is the brainchild of Arc90 lead engineer Elijah Insua.

Discuss

If you have questions about JSDOM or would just like to share your thoughts, you can do so at the Arc90 blog.

ActionScript 3 XPath Library

Wednesday, April 28th, 2010

One of the issues I’ve come across when dealing with XML in ActionScript 3 has been the inability to dynamically execute E4X queries. The need to do so arose several times, and one solution was to use RiaOne’s D.eval API. This solution is pretty robust; it’s a runtime parser/compiler for ActionScript code and it works pretty well. I have a couple of issues with it though. The first is that it’s like using an atomic bomb to kill a fly. When all you want to do is navigate through an XML document at runtime, a tool that can parse the entire ECMAScript specification seems like overkill. My second issue is that it’s a black box with hard to understand, diagnose, and catch runtime errors. At first, I thought that an implementation of just the E4X portions of the spec would provide a solution, but that soon led me into a labyrinthine maze of what to cut and what to keep. I wanted something a lot simpler and that’s where XPath 1.0 enters the picture.

The XPath specification is pretty simple, allowing for the searching (and limiting of those searches) within an XML document that is provided as context. I’m not going to go into how to write XPath, but I’ll point you to the spec for 1.0. I’m a firm believer in not reinventing the wheel, so the first thing I did was look for an XPath library written in ActionScript’s close cousin, JavaScript. It didn’t take much searching to find Form Faces. The project appears to be defunct, but it provided the basis for my implementation. I have optimized the library where possible, but it is still not as fast as the native E4X implementation. The full feature set of the XPath 1.0 specification has been implemented.

One note on how to improve performance: position predicates in the form of /document/element[1] are much faster than boolean predicates in the form of /document/element[@name = 'temp'].

How to use it

The entry point for the library is the com.watchthosecorners.xpath.XPath class. It has two static methods and two instance methods that allow either the evaluation of an XPath query or the selection of a single node. Imagine we have the following XML document for use in our XPath queries (bear in mind that XPath uses 1 as its start index, not 0):

<document>
   <element>Some Value</element>
   <element>Some Other Value</element>
</document>

The following snippet would retrieve the text value of an element. The evaluate method can return a string, a boolean, a number, or a node-set (an array of values):

var string1:* = XPath.evaluate("/document/element[1]/text()", document);
var string2:* = new XPath("/document/element[2]/text()").evaluate(document);
trace(string1) // Output: Some Value
trace(string2) // Output: Some Other Value

var nodeSet:NodeSet = XPath.evaluate("/document/element", document);
trace(nodeSet) // Output: <element>Some Value</element>,<element>Some Other Value</element>

var boolean:Boolean = XPath.evaluate("1 = 1");
trace(boolean) // Output: true
boolean = XPath.evaluate("/document/element[1]/text() = 'Some Other Value'", document);
trace(boolean) // Output: false

var number:Number = XPath.evaluate("count(/document/element)", document);
trace(number) // Output: 2

The snippet below would select a single XML element (the value is returned as the native XML type):

var result1:* = XPath.selectSingleNode("/document/element[1]", document);
var result2:* = new XPath("/document/element[2]").selectSingleNode(document);

trace(result1) // Output: <element>Some Value</element>
trace(result2) // Output: <element>Some Other Value</element>

While the use cases above are simplistic, the XPath library allows for powerful searching of an XML document at runtime. One possible used could be to extend the DataGrid and DataGridColumn classes to support XPath as a value for the dataField property, thereby allowing more complex lookups of values.

Get it

The AS3 XPath Library is hosted on googlecode. It is built with Maven and consists of two modules.

  1. as3xpath-core: This is the core functionality and is all that’s required in a project. (API Docs)
  2. as3xpath-ext-functions: This library contains a small set of functions that can be used in XPath queries, it is not required. (API Docs)

For those who use Maven to manage dependencies, there is a maven repository here and the source for all releases and current development can be viewed here.

Issues

Please report any bugs in the issues section of the googlecode project.

License

AS3 XPath Library is released under the Apache 2.0 license.

Discuss

Please offer feedback in the comments, or email me, Andy Lewisohn, at andrewl@arc90.com.

ActionScript XML Binding

Thursday, February 12th, 2009

Working with XML in ActionScript has been made pretty simple by E4X. But many developers prefer to work with ActionScript objects rather than straight XML. Unfortunately, converting to and from XML is an often laborious, and certainly tedious, task. Java developers may be familiar with Java Architecture for XML Binding (JAXB) and will quickly note that it was the inspiration for ActionScript XML Biinding (ASXB).

ASXB is a concrete implementation of XML binding that used custom metadata as the means of annotation. This is the 0.1 release of ASXB and so it’s fairly rough around the edges and is intended to test the waters, so to speak, of the ActionScript developer community. If the ASXB project seems like it might be of use in your development, please comment on it over in the arc90 blog.


What is this?

The ActionScript XML Binding (ASXB) project is intended to make the marshalling/unmarshalling of XML/ActionScript objects a much easier task. It’s a small library that allows a developer to use custom metadata to annotate his/her ActionScript objects for seamless marshalling and unmarshalling.

How Do I Use It?

To use ASXB in your Flex project, just follow these simple steps:

Download The Code

Click on the icon below to download the source code:

Download

The file contains everything required to build the ASXB project, as well as a compiled release of the ASXB.swc.

Add the code to your Flex or AIR project

You can either add the compiled library, ASXB.swc, to your project’s library path, or include the source directly in your project.

Add compiler settings

Copy flex-config-template.xml to your project and change the name to flex-config.xml. Add the following compiler setting: -load-config+=<path-to-config>/flex-config.xml

Annotate your ActionScript objects

Below is a very basic example of an annotated object.

	[XmlRootElement(name="book")] 	public class Book 	{ 		[XmlAttribute(name="authorFullName")] 		public var author:String; 		 		[XmlAttribute] 		public var dateOfPublication:Date; 		 		[XmlAttribute(name="pageCount")]  		public var pages:int; 		 		[XmlElement] 		public var title:String; 		 		... 	} 

The above object maps to the following XML snippet. When the name of an annotated member is the same as the corresponding XML element or attribute, no name key/value pair is required.

	<book authorFullName="Alastair Reynolds" dateOfPublication="2003-5-27" pageCount="704"> 		<title>Chasm City</title> 	</book> 

Create an instance of XMLService using either MXML or ActionScript.

MXML:

	<arc90:XMLService id="service" url="http://example.url/service/" fault="faultHandler(event)" result="resultHandler(event)"/>   

ActionScript:

	import org.orpheus.xml.bind.XMLService; 	 	var service:XMLService = new XMLService(); 	service.url = "http://example.url/service/" 	service.addEventListener(FaultEvent.FAULT, faultHandler); 	service.addEventListener(ResultEvent.RESULT, resultHandler);   

XMLService functions exactly like mx.rpc.http.HTTPService

To send data to a service just call send, passing an ActionScript object as the parameter, or by setting the request property.

	var book:Book = new Book(); 	book.author = "Alastair Reynolds"; 	book.title = "Chasm City"; 	 	service.send(book); 	 	// or 	 	service.request = book; 	service.send(); 

Any data returned as a result of a service call will be automatically unmarshalled into the appropriate data type. It is accessible via the result property of the ResultEvent object.

	private function resultHandler(event:ResultEvent):void 	{ 		var book:Book = event.result as Book; 		 		trace("You have retrieved " + book.title + " by " + book.author + "."); 		// OUTPUT: You have retrieved Chasm City by Alastair Reynolds.	 	} 

Documentation

Review the complete documentation for a full list of all properties, methods, and annotations of the ActionScript XML Binding project.

Licensing

This arc90 tool is licensed under the BSD license

Discuss ActionScript XML Binding

You can offer feedback on ActionScript XML Binding at the arc90 blog.

Best Buy Remix API client (PHP)

Friday, February 6th, 2009

Best Buy has opened up its retail catalog in hopes that innovative developers will help to expand the company’s online presence. Best Buy Remix (currently in Beta) exposes information about Best Buy products and stores.

Interested? Apply for an API key, download the PHP client library and get started!


What is this?

BestBuy_Service_Remix is a PHP library for placing HTTP calls to the Best Buy Remix API.

How Do I Use It?

To use BestBuy_Service_Remix in your PHP project, just follow these simple steps:

Download The Code From Google Code

Click on the icon below to go get the source from Google Code:


Download

The most recent download will contain source code, usage instructions, and documentation.

Add the code to your PHP project

You’ll need to add the contents of the ‘lib’ folder to your include path.

Create a BestBuy_Service_Remix API client with a valid API key

<?php
require_once('BestBuy/Service/Remix.php');
$remix = new BestBuy_Service_Remix('YourApiKey');

BestBuy_Service_Remix returns a response object containing API response data and HTTP metadata recorded by cURL

Data may be requested in either XML (default) or JSON format.

<?php
require_once('BestBuy/Service/Remix.php');
$remix = new BestBuy_Service_Remix('YourApiKey');
// Retrieve a list of Movies containing the text "Bat"
$result = $remix->products(array('name=bat*','type=Movie'))->query();
if(!$result->isError())
{
echo $result;
}
else if(403 != $result->http_code)
{
// API errors result in an error document with detailed info
echo $result->toSimpleXml()->message;
}
else
{
// 403 errors do not contain a full document, only an h1 message
echo $result->toSimpleXml()->h1;
}

Documentation

Complete documentation is included with each download in the ‘docs’ folder.

Licensing

This library is licensed under a BSD license.

Discuss

Share your thoughts, or just let us know what you’re up to over at the Arc90 blog.

SqlWatcher: Ad-hoc database change monitoring

Thursday, February 5th, 2009

How many times have you needed to debug an application and wished, just wished, you had put better instrumentation in your code? It would have been brilliant if you had logged the key database fields before and after the update. It would have been killer if you had recognized exactly which rows and columns were in play and had a way of confirming that your stored proc is doing what you thought it would.

But you didn’t.

Continue reading»

Yeller

Monday, January 26th, 2009

Yeller is a PHP script that lets a group post messages to a single Twitter account using Yammer. It does this by searching Yammer messages for a special tag (by default #yell) and sending any messages it finds to Twitter. It also pulls replies back from Twitter so the group can participate in conversations.

Continue reading»

Yammer API Client Library

Tuesday, September 23rd, 2008

Update: Yammer recently modified their API to only allow OAuth style authentication. As a result, this library has become defunct. If you update this library to support OAuth, please let us know.

Yammer is a new microblogging service that has been described as “an enterprise version of Twitter”. Instead of asking, “What are you doing?” Yammer asks, “What are you working on?”

Yammer has released their API with some great documentation, so we’ve written a library for building our own tools (RSS feeds, status updates on intranet pages, etc…)

Anyone can start a Yammer account for an organization (defined by email domain), and many services, including IM, SMS, and email integration are free. Optionally, organizations may claim their domain for a fee, allowing for more advanced control and customizations.

Enjoy!


What is this?

The Arc90_Service_Yammer class makes HTTP requests to the Yammer API using PHP and cURL.

How Do I Use It?

To use Arc90_Service_Yammer in your PHP project, just follow these simple steps:

Download The Code

Click on the icon below to download the source code:


Download

The file, Arc90_Service_Yammer.zip, contains the source, usage instructions and phpDoc
generated documentation.

Add the code to your PHP project

You’ll need to add the contents of the ‘lib’ folder (the ‘Arc90′ folder and its contents) to
your include path.

Create an Arc90_Service_Yammer API client with a valid Yammer username (email address) and password

<?php
require_once('Arc90/Service/Yammer.php');
$yammer = new Arc90_Service_Yammer('username', 'password');

Arc90_Service_Yammer returns an Arc90_Service_Yammer_Response object containing the
requested data and all of the HTTP metadata recorded by cURL

Data may be requested in any format supported by Yammer (currently XML and JSON). The default type is JSON.

<?php
require_once('Arc90/Service/Yammer.php');
$yammer = new Arc90_Service_Yammer('username', 'password');
// Gets the 20 most recent messages posted to your domain in JSON format
$response = $yammer->getMessagesAll();
// Print out the data
echo $response->getDataString();
// Casting is also supported. This does the same thing as above.
echo (string) $response;
// Data is also wrapped as an object
foreach($response->messages as $message)
{
print_r($m);
}
// If Yammer returned an error (401, 400, etc), print status code
if($response->isError())
{
echo "Error status: " . $response->http_code;
}
}

Documentation

Review the complete documentation for a full
list of all functions available with Arc90_Service_Yammer.

Licensing

This arc90 tool is licensed under a BSD license.

Discuss

Feel free to offer feedback over on the blog.

Java Encrypter

Tuesday, September 2nd, 2008

Encrypter is a simple Java class for encrypting a java object to text, and later reversing the process. It’s useful for transferring sensitive data over an unencrypted channel, such as in an XML document or email.

DES encryption is performed using Java’s SealedObject class, and Base64 encoding is handled by the public domain Base64 class.

What is this?

A .jar file containing Encrypter class, as well as the original source code.

How do I use it?

Download and extract the archive
Add the target/Encrypter-X.X.jar to your classpath.
Instantiate the class and call its method

Examples are provided below.

Download the code

Click on the icon below to download the source code:

Download

The archive contains the original source code (in src/main/java), JUnit unit tests in (src/test/java) and the complied .jar (at target/Encrypter-X.X.jar).

Examples

Here’s an example of instantiating Encrypter, encrypting an object to a String, and decrypting a String to an object.
Typically, the encrypting and decrypting would be called in separate places and not one after another as in this
example.

package com.arc90.example;
import java.util.ArrayList;
import java.util.List;
import com.arc90.labs.encrypter.Encrypter;
/**
* Example usage of the Encrypter class
*/
public class EncrypterExample
{
public static void main(String[] args)
{
String password = "cW1dm0re";
/*
* Create the object to encrypt (must be Serializable)
*/
List secrets = new ArrayList();
secrets.add(4);
secrets.add(8);
secrets.add(15);
secrets.add(16);
secrets.add(23);
secrets.add(42);
/*
* Encrypt the object into a String named cipherText
*/
Encrypter<List> encrypter = new Encrypter<List>();
String cipherText = encrypter.encryptAndSerialize(secrets, password);
/*
* Print the encrypted String
*/
System.out.println(cipherText);
/*
* Decrypt the String
*/
List reversed = encrypter.deserializeAndDecrypt(cipherText, password);
/*
* Print the decrypted object
*/
for(Integer i : reversed)
{
System.out.println(i);
}
}
}

Licensing

This arc90 tool is licensed under the Creative Commons Attribution-Share Alike 3.0 license.

Discuss Encrypter

You can send feedback on Encrypter by adding a comment to the original blog post.

PHP Twitter API Client

Tuesday, June 3rd, 2008

I’ve been having some fun with Twitter lately.

Twitter’s direct messaging feature is great for automated messaging tasks. With SMS and IM forwarding, I can receive critical updates from a server (or my coffee pot… or whatever) just about anywhere. Good times!

In need of Twitter’s services for a recent side project, I thought it would be nice to have a simple easy-to-use Twitter client that fit in with our existing libraries.

Feedback is definitely welcome. Feel free to email me at mattw@arc90.com with questions, comments or suggestions or post your comments over at the Arc90 blog.

Happy Twittering!


What is this?

The Arc90_Service_Twitter class makes requests to the Twitter API via PHP and cURL.

How Do I Use It?

To use Arc90_Service_Twitter in your PHP project, just follow these simple steps:

Download The Code From Google Code

Click on the icon below to go get the source from Google Code:


Download

The most recent download will contain source code, usage instructions, and documentation

Add the code to your PHP project

You’ll need to add the contents of the ‘lib’ folder to your include path.

Create an Arc90_Service_Twitter API client with a valid Twitter username and password

<?php
require_once('Arc90/Service/Twitter.php');
$twitter = new Arc90_Service_Twitter('username', 'password');

Arc90_Service_Twitter returns an Arc90_Service_Twitter_Response object containing the
requested data and all of the HTTP metadata recorded by cURL

Data may be requested in any format supported by Twitter (XML, JSON, and sometimes RSS and ATOM). The default type
is JSON.

<?php
require_once('Arc90/Service/Twitter.php');
$twitter = new Arc90_Service_Twitter('username', 'password');
try
{
// Gets the authenticated user's friends timeline in XML format
$response = $twitter->getFriendsTimeline('xml');
// Print the XML response
echo $response->getData() . "\n";
// If Twitter returned an error (401, 503, etc), print status code
if($response->isError())
{
echo $response->http_code . "\n";
}
}
catch(Arc90_Service_Twitter_Exception $e)
{
// Print the exception message (invalid parameter, etc)
print $e->getMessage();
}

Documentation

Review the complete documentation for a full list of all functions available with Arc90_Service_Twitter.

Note: Up-to-date documentation is included with each release in the ‘docs’ folder.

Licensing

This arc90 tool is licensed under a BSD license.

Discuss Arc90_Service_Twitter

You can offer feedback on Arc90_Service_Twitter at the arc90 blog.

jQuery Reverse Order plugin

Thursday, May 22nd, 2008

Ever want to reverse the order of a group of DOM elements? Or want to give your user the option?

What is this?

jQuery Reverse Order uses jQuery to reverse the order of DOM elements on your page.

How Do I Use It?

To use jQuery Reverse Order on your site or blog, just follow these simple steps:

Download The Code

Click on the icon below to download the source code:

Download

The file, jquery_reverseorder.zip, contains the script, an example page, and the jQuery library. Once downloaded, unzip and upload the script to a relevant location on your hosted site.

Link To The Javascript

Add a link to the jQuery library and to the javascript file in the page(s) you’d like jQuery Reverse Order implemented. Remember to adjust the path to properly point to the location of the javascript file:

 

A packed version is also included in the .zip called "jquery_reverseorder.packed.js".

Choosing which elements to reverse

Create a collection of DOM elements inside a common parent. Here’s an example:

item 1

item 2

item 3

item 4

Then add a single line of javascript, referencing the items to be reversed, to reverse the order:

$('#items .item').reverseOrder();

You could also use:

$('#items p').reverseOrder();

Examples

Here’s another example using the native unordered list as a collection:

  • item 1
  • item 2
  • item 3
  • item 4

Then add a single line of javascript to reverse the order:

$('ul li').reverseOrder();

You can see more examples and uses of jQuery Reverse Order by clicking here.

Supported Browsers

Currently, the jQuery Reverse Order script has been tested and confirmed on the following browsers:

  • Internet Explorer 6.0+
  • Mozilla Firefox 2.0+
  • Apple Safari 2.0+
  • Opera Version 9.0

Licensing

This arc90 tool is licensed under the Creative Commons Attribution-Share Alike 3.0 license.

Discuss jQuery Reverse Order

You can send feedback on jQuery Reverse Order at the arc90 blog.