Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS 

Creating a bucket in Amazon S3 through an irb session

1) Log into an irb session, and enter your S3 login details.
require 'rubygems'
require 'aws/s3'

  AWS::S3::Base.establish_connection!(
    :access_key_id     => 'REPLACE_ME',
    :secret_access_key => 'REPLACE_ME'
  )

output:
=> #<AWS::S3::Connection:0xb75e0594 @http=#<Net::HTTP s3.amazonaws.com:80 open=false>, @secret_access_key="", @options={:server=>"s3.amazonaws.com", :access_key_id=>"", :port=>80, :secret_access_key=>"", :persistent=>true}, @access_key_id="19S45GYAGWK8DC2B8VG2">

2) Browse the existing buckets.
AWS::S3::Service.buckets

output:
=> [#<AWS::S3::Bucket:0xb75cc850 @object_cache=[], @attributes={"name"=>"ogg.twitteraudio.com", "creation_date"=>Sat Apr 26 10:40:16 UTC 2008}>, #<AWS::S3::Bucket:0xb75cc83c @object_cache=[], @attributes={"name"=>"t1000", "creation_date"=>Fri Apr 25 21:35:21 UTC 2008}>, #<AWS::S3::Bucket:0xb75cc814 @object_cache=[], @attributes={"name"=>"t2000", "creation_date"=>Fri Apr 25 21:53:15 UTC 2008}>]

3) Browse the buckets in a programmatical way.
AWS::S3::Service.buckets.each {|b| puts b.name}

output:
ogg.twitteraudio.com
t1000
t2000


4) Add a new bucket called t3000.
AWS::S3::Bucket.create('t3000')

output:
=> true

5) Observe adding the bucket again doesn't cause an error.
AWS::S3::Bucket.create('t3000')

output:
=> true

6) View the buckets again.
AWS::S3::Service.buckets

output:
=> [#<AWS::S3::Bucket:0xb75cc850 @object_cache=[], @attributes={"name"=>"ogg.twitteraudio.com", "creation_date"=>Sat Apr 26 10:40:16 UTC 2008}>, #<AWS::S3::Bucket:0xb75cc83c @object_cache=[], @attributes={"name"=>"t1000", "creation_date"=>Fri Apr 25 21:35:21 UTC 2008}>, #<AWS::S3::Bucket:0xb75cc814 @object_cache=[], @attributes={"name"=>"t2000", "creation_date"=>Fri Apr 25 21:53:15 UTC 2008}>]

Note: You would expect t3000 to be in there however it didn't appear possibly because of the bucket permissions.

7) Let's then look for bucket t3000.
t3000 = AWS::S3::Bucket.find('t3000')

output:
=> #<AWS::S3::Bucket:0xb76df724 @object_cache=[], @attributes={"prefix"=>nil, "name"=>"t3000", "marker"=>nil, "max_keys"=>1000, "is_truncated"=>false, "xmlns"=>"http://s3.amazonaws.com/doc/2006-03-01/"}>

8) Now that we've found the bucket let's upload a text file called works.txt.
file = "works.txt"

output:
=> "works.txt"
AWS::S3::S3Object.store(file, open(file), 't3000', :access => :public_read)

output:
=> #<AWS::S3::S3Object::Response:0x-608926458 200 OK>

9) Setting the file access to :public_read allows us to view the file from the http location http://t3000.s3.amazonaws.com/works.txt

References:
http://amazon.rubyforge.org/
upload_to_s3 - Ruby S3 upload client [dzone.com]

*update: 14:30 30 April 2008 *
I didn't use Bucket.objects(:reload) which is the reason why the bucket t3000 didn't show up with the statement Service.buckets

Reference: spatten design - Amazon S3, Ruby and Rails slides [spattendesign.com]

jaiku.py

// Set and view Jaiku statuses

#!/usr/bin/env python

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="28 Jun 2007"
__copyright__="Copyright 2007 Andrew Pennebaker"
__license__="GPL"
__version__="0.0.1"
__URL__="http://snippets.dzone.com/posts/show/4223"

import sys, getopt, urllib2, xmlrpclib

import configreader

STATUS_MODE="STATUS"
VIEW_MODE="VIEW"

def set_status(settings, status):
	s=xmlrpclib.ServerProxy(settings["xmlrpcurl"])
	
	calldata={"user":settings["username"], "personal_key":settings["personalkey"], "message":status, "location":settings["location"]}
	
	try:
		s.presence.send(calldata)
	except:
		raise "Could not connect."

def view_status(settings):
	item=settings["itemdelimeter"]
	t1=settings["titledelimeter1"]
	t2=settings["titledelimeter2"]

	try:
		instream=urllib2.urlopen(
			settings["feedurlstart"]+settings["username"]+settings["feedurlend"]
		)

		for line in instream:
			if item in line:
				break

		title=instream.readline()

		instream.close()

		status=title[title.index(t1)+len(t1):title.index(t2)]

		return status

	except IOError, e:
		raise "Could not connect."

def usage():
	print "Usage: %s [options]" % (sys.argv[0])
	print "\nWithout any options, uses status mode. Leftover args are concatenated to form message."
	print "\n-u|--username <username> specified in jaiku.conf"
	print "-p|--personal-key <key>"
	print "-l|--location <location>"
	print "-s|--status mode"
	print "-v|--view status"
	print "-c|--config <configfile>"
	print "-h|--help"

	sys.exit()

def main():
	global STATUS_MODE
	global VIEW_MODE

	systemArgs=sys.argv[1:]

	mode=STATUS_MODE

	settings={
		"config":"jaiku.conf",
		"xmlrpcurl":"http://api.jaiku.com/xmlrpc",
		"feedurlstart":"http://",
		"feedurlend":".jaiku.com/feed/atom",
		"itemdelimeter":"<entry>",
		"titledelimeter1":"<title>",
		"titledelimeter2":"</title>",
		"username":"mcandre",
		"personalkey":"",
		"location":""
	}

	optlist, args=[], []

	try:
		optlist, args=getopt.getopt(systemArgs, "u:p:l:svc:h", ["username=", "personal-key=", "location=", "status", "view", "config=", "help"])
	except e:
		usage()

	for option, value in optlist:
		if option=="-c" or option=="--config":
			settings["config"]=value

	try:
		configreader.load(open(settings["config"], "r"), settings)
	except IOError, e:
		pass

	for option, value in optlist:
		if option=="-h" or option=="--help":
			usage()

		elif option=="-u" or option=="--username":
			settings["username"]=value
		elif option=="-p" or option=="--personal-key":
			settings["personalkey"]=value
		elif option=="-l" or option=="--location":
			settings["location"]=value
		elif option=="-s" or option=="--status":
			mode=STATUS_MODE
		elif option=="-v" or option=="--view":
			mode=VIEW_MODE

	if mode==STATUS_MODE:
		if len(args)<1:
			usage()

		message=" ".join(args)

		set_status(settings, message)
	elif mode==VIEW_MODE:
		print view_status(settings)

if __name__=="__main__":
	try:
		main()
	except KeyboardInterrupt, e:
		pass

tiny.py

#!/usr/bin/env python

"""Converts long URLs to tiny URLs, with either tinyurl, urltea, or a custom url."""

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="22 Jun 2007 - 24 Jun 2007"
__copyright__="Copyright 2007 Andrew Pennebaker"
__license__="GPL"
__version__="0.0.1"
__URL__="http://snippets.dzone.com/posts/show/4195"
__credits__="http://lateral.netmanagers.com.ar/weblog/2007/04/08.html#BB548"

import sys, getopt, urllib

import configreader

def tiny(url, settings):
	try:
		encodedurl=settings["posting url"]+urllib.urlencode({"url":url})
		instream=urllib.urlopen(encodedurl)
		tinyurl=instream.read()
		instream.close()

		if len(tinyurl)==0:
			return url

		if settings["service"]=="urltea" and len(settings["description"])>0:
				tinyurl+=settings["description delimeter"]+settings["description"]

		return tinyurl
	except IOError, e:
		raise "Could not connect."

def usage():
	print "Usage: %s [options] <url1> <url2> <url3> ..." % (sys.argv[0])
	print "\nDefaults to urlTea unless specified in options or a config file."
	print "\n-s|--service [tinyurl|urltea]"
	print "-u|--custom-url <posting url>"
	print "-d|--description <comment> May only be used with urltea."
	print "-c|--config <configfile>"
	print "-h|--help (usage)"

	sys.exit()

def main():
	systemArgs=sys.argv[1:]
	oplist, args=[], []

	settings={
		"config":"tiny.conf",
		"service":"urltea",
		"urltea url":"http://urltea.com/api/text/?url=",
		"tinyurl url":"http://tinyurl.com/api-create.php?",
		"description delimeter":"?",
		"description":""
	}

	try:
		optlist, args=getopt.getopt(systemArgs, "s:u:d:c:h", ["service=", "custom-url=", "description=", "config=", "help"])
	except:
		usage()

	for option, value in optlist:
		if option=="-c" or option=="--config":
			settings["config"]=value

	try:
		configreader.load(open(settings["config"], "r"), settings)
	except IOError, e:
		pass

	for option, value in optlist:
		if option=="-h" or option=="--help":
			usage()
		elif option=="-s" or option=="--service":
			settings["service"]=value
		elif option=="-d" or option=="--description":
			settings["description"]=value

	if settings["service"]!="urltea" and len(settings["description"])>0:
		usage()

	try:
		settings["posting url"]=settings[settings["service"]+" url"]
	except:
		usage()

	for option, value in optlist:
		if option=="-u" or option=="--custom-url":
			settings["posting url"]=value

	if len(args)<1:
		usage()

	for u in args:
		print tiny(u, settings)

if __name__=="__main__":
	try:
		main()
	except KeyboardInterrupt, e:
		pass

J2ME - Create Service Bluetooth

// Create Service Bluetooth

import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class ServerChat
{
	private static final String CHATTANDO_UUID = "A1A2A3A4A5A6A7A8A9A0B1B2B3B4B5B6";
	private static final String CHATTANDO_SERVICE = "Chattando";
	
	private boolean isReady = false;
	
	private StreamConnection stream_connection;
	private StreamConnectionNotifier stream_connection_notifier;
	
	public ServerChat()
	{
		startServerChatBluetooth();
	}
	
	// Apre il servizio per la Chat
	public void startServerChatBluetooth()
	{
		new Thread()
		{
			public void run()
			{
				try
				{
					LocalDevice.getLocalDevice().setDiscoverable(DiscoveryAgent.GIAC);
				}
				catch(Exception error)
				{
					error.printStackTrace();
				}
				
				try
				{
					stream_connection_notifier = (StreamConnectionNotifier) Connector.open("btspp://localhost:" + CHATTANDO_UUID + ";name=" + CHATTANDO_SERVICE);
				}
				catch(Exception error)
				{
					error.printStackTrace();
				}
				
				stopServerChatBluetooth();
				
				// Mette in ascolto il Server della Chat
				isReady = true;
				
				try
				{
					while(isReady)
					{
						System.out.println("Sono in ascolto...");
						
						stream_connection = stream_connection_notifier.acceptAndOpen();
						
						System.out.println("Client Connected");
					}
				}
				catch(Exception error)
				{
					error.printStackTrace();
				}
			}
			
		}.start();
	}

	// Chiude il servizio per la Chat
	public void stopServerChatBluetooth()
	{
		if(isReady)
		{
			isReady = false;
			
			try
			{
				stream_connection_notifier.close();
			}
			catch(Exception error)
			{
				error.printStackTrace();
			}
		}
	}
}

J2ME - Search Service Bluetooth

// Example Search Service Bluetooth

import java.util.Vector;

import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;

public class ClientChat implements DiscoveryListener
{
	private static final String CHATTANDO_UUID = "A1A2A3A4A5A6A7A8A9A0B1B2B3B4B5B6";
	private static final String CHATTANDO_SERVICE = "Chattando";

	protected Chattando midlet;
	
	private boolean searchDone = false;
	
	private DiscoveryAgent discovery_agent;
	
	private Vector remote_device;
	private Vector device_found;
	
	public ClientChat(Chattando midlet)
	{
		this.midlet = midlet;
		
		startScanBluetoothDevices();
	}
	
	// Avvia la ricerca dei dispositivi Bluetooth
	public void startScanBluetoothDevices()
	{
		try
		{
			remote_device = new Vector();
			device_found = new Vector();
			
			discovery_agent = LocalDevice.getLocalDevice().getDiscoveryAgent();
			discovery_agent.startInquiry(DiscoveryAgent.GIAC, this);
		}
		catch(Exception error)
		{
			error.printStackTrace();
		}
	}
	
	// Stoppa la ricerca dei dispositivi Bluetooth
	public void stopScanBluetoothDevices()
	{
		discovery_agent.cancelInquiry(this);
	}

	public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) 
	{
		// Aggiungo il dispositivo solo se e' un computer (0x0100) o un cellulare (0x0200)
		if(cod.getMajorDeviceClass() == 0x0100 || cod.getMajorDeviceClass() == 0x0200)
			remote_device.addElement(btDevice);
	}

	public void inquiryCompleted(int discType)
	{
		switch(discType)
		{
			case DiscoveryListener.INQUIRY_COMPLETED:
														System.out.println("Device Search Completed");
														
														break;
				
			case DiscoveryListener.INQUIRY_ERROR:
														System.out.println("Device Search Error");
														
														break;
				
			case DiscoveryListener.INQUIRY_TERMINATED:
														System.out.println("Device Search Terminated");
														
														break;
		}
		
		try
		{
			for(int i=0, cnt=remote_device.size(); i<cnt; i++)
			{
				discovery_agent.searchServices(new int[]{ 0x0100, 0x0200 }, new UUID[]{ new UUID(0x0003), new UUID(CHATTANDO_UUID, false) }, (RemoteDevice) remote_device.elementAt(i), this);
				waitForSearchDone();
			}
		}
		catch(Exception error)
		{
			error.printStackTrace();
		}
	}

	// Aspetta che la ricerca dei servizi per il dispositivo sia terminata
	private void waitForSearchDone()
	{
		searchDone = false;
		
		try
		{
			while(!searchDone)
			{
				synchronized(this)
				{
					this.wait();
				}
			}
		}
		catch(Exception error)
		{
			
		}
	}
	
	public void serviceSearchCompleted(int transID, int respCode)
	{
		switch(respCode)
		{
			case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
																		System.out.println("Service Search Completed");
																		
																		break;
				
			case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
																		System.out.println("Service Search Device not Reachable");
																		
																		break;
				
			case DiscoveryListener.SERVICE_SEARCH_ERROR:
																		System.out.println("Service Search Error");
																		
																		break;
				
			case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
																		System.out.println("Service Search No Records");
																		
																		break;
				
			case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
																		System.out.println("Service Search Terminated");
																		
																		break;
		}
		
		searchDone = true;
		
		// Risveglia il processo in attesa del completamento della ricerca dei servizi per un dispositivo
		synchronized(this)
		{
			this.notifyAll();
		}
	}

	public void servicesDiscovered(int transID, ServiceRecord[] servRecord)
	{
		for(int i=0, cnt=servRecord.length; i<cnt; i++)
		{
			if(((String) servRecord[i].getAttributeValue(0x0100).getValue()).equalsIgnoreCase(CHATTANDO_SERVICE))
			{
				device_found.addElement(servRecord[i].getHostDevice());
			}
		}
	}
}

Mongrel on Win32 as Service

Mongrel now has support for running as a Win32 service right out of the box. The support is still rough but works well enough that we decided to release it. You can thank Luis Lavena for working on this and making it so nice.

After you do the gem install, find a Rails application you want to run and do:
$ mongrel_rails_service install -n myapp -r c:\my\path\to\myapp -p 4000 -e production
$ mongrel_rails_service start -n myapp

Now hit the port and poof, works. Stopping the app is just done with:
$ mongrel_rails_service stop -n myapp

And, you can even set the CPU processor affinity for the service when yourun the install command. Can’t even do that on POSIX yet. Now that’s hot.

If you run into an app that’s not running right, my suggestion is to run it with the regular mongrel_rails runner:
$ cd c:\my\path\to\myapp
$ mongrel_rails start -p 4500

Since that will spit out error messages and stuff to the console. Use CTRL-Pause/Break to stop.
« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS