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-9 of 9 total  RSS 

Post to both Jaiku and Twitter

This XML code is the ProjectX API to post to both Twitter and Jaiku. This is a follow-up example from Post to Jaiku using ProjectX API [dzone.com]

xml_project = <<PROJECT
<project name='micro_blog'>
  <methods>
    <method name='post2jaiku'>
      <params>
        <param var='user' val='YourJaikuUserName'/>
        <param var='msg' val='YourMessage'/>
        <param var='location' val='YourCity'/>
        <param var='apikey' val='YourApiKey'/>
      </params>
    </method>
    <method name='post2twitter'>
      <params>
        <param var='user' val='YourTwitterUserName'/>
        <param var='msg' val='YourMessage'/>
        <param var='password' val='YourPassword'/>
      </params>
    </method>    
  </methods>
</project>"
PROJECT

Post to Jaiku using ProjectX API

This Ruby code uses the ProjectX API on rorbuilder.info to send a post to Jaiku.

Prerequisites:
1) You have a Jaiku account. see http://jaiku.com/
2) You know your Jaiku API key. see http://api.jaiku.com/

#!/usr/bin/ruby
# file: projectx_client.rb

require 'net/http'
require 'rexml/document'
include REXML

class ProjectXClient
  attr :doc
  def initialize(raw_url)
    url = URI.escape(raw_url)
    xml_data = Net::HTTP.get_response(URI.parse(url)).body
    @doc = Document.new(xml_data)
  end
  
end

if __FILE__ == $0

xml_project = <<PROJECT
<project name='jaiku'>
  <methods>
    <method name='post'>
      <params>
        <param var='user' val='YourJaikuUserName'/>
        <param var='msg' val='YourMessage'/>
        <param var='location' val='YourCity'/>
        <param var='apikey' val='YourApiKey'/>
      </params>
    </method>
  </methods>
</project>"
PROJECT
  
  pxc = ProjectXClient.new("http://rorbuilder.info/api/projectx.cgi?xml_project=" + xml_project)
  doc = pxc.doc
  puts doc
    
end



You can also pass the url including xml into the address bar and it will post to Jaiku successfully.
eg.
http://rorbuilder.info/api/projectx.cgi?xml_project="<project name='jaiku'><methods><method name='post'><params><param var='user' val='jrobertson'/><param var='msg' val='testing 223'/><param var='location' val='London'/><param var='apikey' val='5ugr6ttr754y214445'/></params></method></methods></project>"

Note:
Your api key is not in any way stored by the website rorbuilder.info.
Rorbuilder.info is a 3rd party developer website which is not part of Jaiku.com.

Introduction to Distributed Ruby

This code demonstrates a client server architecture. I executed the file simple_service.rb on my Ubuntu server (Donatello - 192.168.1.10), then from the CLI output I copied the server uri into the clipboard. I then executed the simple_client.rb on my Ubuntu desktop (Cryton - 192.168.1.3) while passing in the uri as an argument.
#!/usr/bin/env ruby -w
# simple_service.rb
# A simple DRb service

# load DRb
require 'drb'

# start up the DRb service
DRb.start_service nil, []

# We need the uri of the service to connect a client
puts DRb.uri

# wait for the DRb service to finish before exiting
DRb.thread.join

output: druby://donatello.mydomain.com:47159

#!/usr/bin/env ruby -w
# simple_client.rb
# A simple DRb client

require 'drb'

DRb.start_service

# attach to the DRb server via a URI given on the command line
remote_array = DRbObject.new nil, ARGV.shift

puts remote_array.size

remote_array << 1

puts remote_array.size


from the command line
> ./simple_client.rb druby://192.168.1.10:47159


output:
0
1


Note: I substituted the domain name with the ip address because the name in question was not stored within the DNS settings.

Reference: Introduction to Distributed Ruby (DRb) [segment7.net]

Devuelve el Referer limpio

// Limpia y devuelve el REFERER

	function getReferer(){
		// limpia el referer 
		$ref = $_SERVER['HTTP_REFERER'];
		$web = str_replace(array('http://','www.'),'',$ref);
		$web = substr($web,0,strpos ($web, '/'));
		if(!empty($web)):
			// retorna el referer limpio
			return $web;
		else:
			// sin referer
			return 'jane.es';
		endif;
	}

recupera datos del visitante

	function getLocation( $ip ) {
		
		static $location = array();
		
		if( !isset( $location[$ip] ) ) {
			$url = "http://www.hostip.info/api/get.html?ip=" . $ip . "&position=true&raandom=" . rand(0,500);
			/* cURL */
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$data = curl_exec($ch);

			if ( curl_errno( $ch ) ) {
				print "Error: ".curl_error($ch);
			} else {
				curl_close($ch);
				$lines = split ("\n", $data);
				foreach($lines as $l):
					$prop = split(':',$l);
					$location[$ip][trim($prop[0])] = addslashes(trim($prop[1]));
				endforeach;
		   }
			
		}
		return $location[$ip];
	}

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());
			}
		}
	}
}

A Client For the XML-RPC Servlet

// When combined with the Apache XML-RPC library this code
// will let you call the servlet in the snippet "An XML-RPC
// Servlet". Of course, since XML-RPC is pretty ubiquitous
// you can also use this code to call servers in dozens of
// other languages as well.

import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.xmlrpc.XmlRpcClient;

public class XMLRPCTestClient {
    private static final String serverAddress = 
	"http://localhost:8080/lol/remoteapi";
    private static Log log = LogFactory.getLog(XMLRPCTestClient.class);
    
    /** Creates a new instance of XMLRPCTestClient */
    public XMLRPCTestClient(String address) {
        try {
            XmlRpcClient xmlrpc = new XmlRpcClient(address);

            Vector params = new Vector();
            params.addElement("Hello World! Hello!");

            try {
                // this method returns a string
                String result = (String) xmlrpc.execute("echo.echo", params);
                System.out.println(result);
            } catch (Exception e) {
                log.error("The remote procedure call failed.", e);
            }
        } catch (java.net.MalformedURLException mue) {
            log.error(
                "The address given for the XML-RPC interface is bad: " + address);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        XMLRPCTestClient xmlRPCTestClient = new XMLRPCTestClient(
            serverAddress);
    }
}

Upload file with http client (multipart/form-data)

def post_multipart(host, selector, fields, files):
    """
    Post fields and files to an http host as multipart/form-data.
    fields is a sequence of (name, value) elements for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be uploaded as files
    Return the server's response page.
    """

See the rest of the implementation here
« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS