Almighty Bus Error

Blog about computer science, code snippets and tips.

GitHub repository with examples here.
Currently a Computer Engineering student at FCT/UNL.
October 14, 2009 at 11:42pm
Tags: Introduction  Java  RMI 

Comments (View)

Java: Remote Method Invocation

The Java RMI (Remote Method Invocation) is a way to create distributed services. It is composed of RMIRegistry which is a name registry which saves the resources available (servers) in a JVM (Java Virtual Machine). The registry is, however, accessible through different JVM’s when configured.

Since all the invocations are remote, most arguments are passed by value. The exception is when an object the implements an interface that extends Remote. A server is passed by reference, since its concept (RemoteObject) requires that the information must to be consistent between all the clients accessing it.

Considering that the server object would be passed by value like any other argument. This means that for the server to be consistent between all clients, it would need for each client to relay the local changes of each individual server to the central server, this creates alot of useless workload since its easier to just change the central server directly, it would save CPU cycles and network traffic on the client side used to calculate the changes and the central server load doesn’t change.

Interface

public interface IStuffServer extends Remote { public void doStuff() throws RemoteException; }

Class

public class StuffServer extends UnicodeRemoteObject implements IInfoReceiver { StuffServer() throws RemoteException { super(); } public void doStuff() { System.out.println("Stuff done."); } }

Every method of a class which extends Remote might throw a RemoteException (network connectivity).

Registering a resource

To create a registry there is a static method in the class LocateRegistry named createRegistry which receives an integer that specifies the port in which the registry will listen for requests. For the registry to be able to communicate with other JVM’s, it is needed to enable it by defining a policy.

policy.all

grant { permission java.security.AllPermission "", ""; }; Please bear in mind this might be insecure for critical applications.

Creating a “public” registry
System.getProperties().put("java.security.policy", "policy.all");

if (System.getSecurityManager() == null) {
    System.setSecurityManager(new RMISecurityManager());
}

try { // start rmiregistry
    LocateRegistry.createRegistry(1099);
} catch (RemoteException e) 
{   /* registry already created*/   }

InfoServerImpl server = new InfoServerImpl();
Naming.rebind("/StuffServer", server);
System.out.println("StuffServer bound in registry");

After creating the registry, the static class Naming is used to bind a name to the class using the method rebind, which in the example is “/StuffServer”. This name is only known by the registry in the current JVM.

A registry can be accessed by a simple netbios-like link, for example “//localhost/StuffServer”.

Obtaining Server Reference

To obtain the server object reference the static Naming class is used again, this time with the lookup method. IInfoServer server = null; try { server = (IInfoServer) Naming.lookup("//localhost/StuffServer"); } catch(RemoteException e) { System.out.println("Server not found"); }

After the server reference is obtained all the interaction to it is the same of a local object, except it might fail/be slower because of network connectivity issues. server.doStuff();

The previous will print “Stuff done.” at the server’s console.

That was it about Java’s RMI. For more information go here.

Thank you for reading!

August 25, 2009 at 8:06pm
Tags: FTP  Python 

Comments (View)

FTP in Python

In Python, to create and maintain a FTP communication, the ftplib or urllib (explained in a future post) can be used.

Creating a FTP connection

from ftplib import FTP
try:
    conn = FTP('almightybuserror.com')
except:
    print "Could not connect to almightybuserror.com."
    return

Logging in…

For anonymous log in: try: conn.login() except: print "No anonymous connections allowed." return

Otherwise:

try:
    conn.login(user, passwd)
    print conn.getwelcome()
except:
    print "Wrong username or password."
    return

Sending commands and handling response.

To send commands (or requests) to the server there is a method for each command which can be consulted here, however I will show an example of an binary file download request.

try:
    conn.cwd('/stuff/more/misc/stuff/')
except:
    print "No such folder!"
    return
file = open('stuff', 'w')
try:
    conn.retrbinary('RETR stuff', file.write) 
    # file.write acts as a function pointer
except:
    print "Couldn't download stuff..."
finally:
    file.close()

Check downloader.py in github for a more complete example.

August 22, 2009 at 5:51pm
Tags: HTTP  Python 

Comments (View)

HTTP in Python

To create and HTTP connection we use the httplib module which provides some simple yet effective methods to create a connection and send requests to an HTTP server. The module urllib can also be used and is easier, does, however only perform GET requests (explained in a future post).

Creating a connection

To create a connection, the method HTTPConnection does the job. For example:

import httplib
try:
    http = httplib.HTTPConnection('almightybuserror.com')
except:
    print 'Could not connect...'
    return

Sending a request

To send a request, a connection object is needed (we’ll use http from the previous example):

http.request("GET", "/")

Getting a response

To obtain a response, the getResponse() method is used. From this method we get a HTTPResponse object.

response = http.getResponse()
if response.status == httplib.OK:
    file = open('example.html', 'w')
    file.write(response.read())
    file.close()
else:
    print 'Error: %s %s' % (response.status, response.reason)
    return

For a more complete example check downloader.py in github.

August 13, 2009 at 5:42pm
Comments (View)

Scripts and Tools Repository

I recently created a github repository for my tools, it can be found here.

Feel free to check it out!

August 4, 2009 at 3:12pm
Comments (View)

Permalink
The Comic Massacre

By Shello, original can be found here.

The Comic Massacre

By Shello, original can be found here.

August 3, 2009 at 9:49pm

Comments (View)

Snippet.Py: Getting an image resolution

Using PIL (Python Image Library) it is possible to get the width and height of a image using the property size.

The following example will take an undefined number of arguments and print all the resolutions:

import Image
import sys

def main():
    argv = sys.argv[1:]
    if (len(argv) == 0):
        print "No file given!"
    else:
        for name in argv:
            img = Image.open(name)
            print name + ": %d %d" % img.size

if __name__ == "__main__":
    main()

Credit for the snippet goes to meqif. The code can also be found at git.

June 20, 2009 at 2:01pm
Comments (View)

June 19, 2009 at 10:14pm
Tags: Comedy 

Comments (View)

Permalink

Source The Daily Show

June 10, 2009 at 3:03pm
Comments (View)

June 5, 2009 at 10:12pm
Comments (View)