Monday, August 5, 2013

Java RMI: Client timeout

Creating a timeout for Java RMI client is important  since LocateRegistry.getRegistry would make your application unresponsive when the Java RMI server is not available. To create a timeout at the client-side, I suggest you to use ExecutorService. The following codes is an example how to use it:

Suppose you have your localhost listening on port 1099 for RMI and your server serve an interface

public interface RMIService() {
  public String sayHello throws RemoteException;
}

Then at your client app, you do this

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Callable<Object>() {
 

  @Override
  public Object call() throws Exception {
    String host = "localhost";
    int port = 1099;
    RMIService service = (RMIService) LocateRegistry

      .getRegistry(host, port).lookup("RMIService");
    System.err.println(service.sayHello());
    return null;
  }


});
 

try {
  future.get(5, TimeUnit.SECONDS);

} catch (InterruptedException | TimeoutException |
    ExecutionException e) {
  System.err.println(e.getMessage());

}

The above code will try executing the remote method and will throw exception if  the lookup time exceeds 5 seconds.

Hope this helps. :)

Monday, February 18, 2013

Java EE: Persists entity beans with generated primary key (SQL Server)

In developing an enterprise application in Java EE, sometimes you would come across a database table with auto-generated primary key. If you're using NetBeans to generante entity beans from a database, you would get something like this:

@Entity
@Table(name = "your_table_name")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "YourTableName.findByTheId", ... )})
public class YourTableName implements Serializable {
    @Id
    @Basic(optional = false)
    @NotNull
    @Column(name = "the_id")
    private Integer theId;


    ...
}

But if you try to persists an instance of the entity bean, you would get an error and you would not be able to alter your database. This is because when you try to persist the instance you would do this

YourTableName yourTableName = new YourTableName();
yourTableName.setFooBarField("foobar"); //example field in table

em.persists(yourTableName);

You could not set the yourself, since it's suppose to be autogenerated by the database. So, in order to solve this, you have to edit the generated entity beans, by adding GeneratedValue annotation to the primary key variable, and also remove the NotNull annotation, like so:

@Id
@Basic(optional = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "the_id")
private Integer theId;

You have to remove @NotNull since, during persisting, you does not set the value for the primary key. Not removing this would throw an error (at least in my case).

Hope this would help. :) 

Tuesday, February 5, 2013

Java: Base64 Encode

I used this function to encode a string using base64 encoding for my java card applet.

public static String base64Encode(String s) {
    String table="ABCDEFGHIJKLMNOPQRSTUVWXYZ";

            + "abcdefghijklmnopqrstuvwxyz0123456789+/";
    String b="";
    String r="";
    int pad;
       
    for (int c : s.toCharArray()) {
        b+=rjust(Integer.toBinaryString(c), 8, "0");
    }
           
    for (int i=0; i<b.length(); i+=6) {
        r+=table.charAt(Integer.parseInt(ljust(b.substring(i, i+6), 6, "0"), 2));
        pad=6-b.substring(i, i+6).length();
        switch (pad) {
            case 0: r+=""; break;
            case 4: r+="=="; break;
            case 2: r+="="; break; }                  
    }
    return r;

}

Both rjust and ljust that you can find in the function above are custom functions similar to python's rjust and ljust.

Monday, January 28, 2013

SQL Server notes

Rename a field (or column) in a table:
EXEC sp_rename 'table_name.old_name', 'new_name', 'COLUMN';

sp_rename is a SQL Server function name.

Friday, December 21, 2012

Fedora 17: Open port for TCP connection

To open a port for TCP connection you have to edit /etc/sysconfig/iptables and append the following line before the COMMIT line

-A INPUT -m state --state NEW -m tcp -p tcp --dport <PORT> -j ACCEPT

And then restart the iptables service by executing

service iptables restart

*EDIT*
I created this post before knowing that you could actually use iptables directly as below :P :

# iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport <PORT> -j ACCEPT

You should list your iptables rules first to check whether there's any DROP rule. If your new rule comes after a rule that DROPs any connection on you target port, the port you're trying to open will stay closed. If there's a DROP rule, use -I (insert) instead:

# iptables -I INPUT <rulenum> -m state --state NEW -m tcp -p tcp --dport <PORT> -j ACCEPT

where <rulenum> is the rule index in the chain. and <PORT> is your target port.

Friday, December 14, 2012

Python: Fun with sockets (remote desktop)

Server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

#!/usr/bin/python

import os
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)

client, addr = s.accept()

cmd = s.recv(1024)
try:
    os.system(cmd)
    client.sendall("OK")
except:
    client.sendall("FAIL")
client.close()

Client
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/python

import socket
import sys

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(sys.argv[1])

data = s.recv(32)

print data
s.close()
print "Received: '%s'"%data

Wednesday, November 28, 2012

Web programming with python and apache: Webserver index page (index.py)

To use python in a web server instead of php, you need to enable cgi-script in your httpd.conf using
AddHandler cgi-script .cgi .py
and you use
ScriptAlias /cgi-bin/ "/your/own/dir/for/cgi-bin/"
to tell apache the script the location of the scripts to be executed.

But if you want the script to handle the webserver index page as index.html, index.php does, follow the following steps:
  1. Edit your root directory settings to execute cgi scripts and handle .py files by writing:
    <Directory /your/root/dir>
      Options +ExecCGI
      AddHandler cgi-script .cgi .py
    </Directory>
  2.  Then set your DirectoryIndex as index.py as so:
    DirectoryIndex index.py

 

index.py "Hello, World!"

#!/usr/bin/python

import cgitb
cgitb.enable()

print "Content-Type: text/html;charset=utf-8\r\n" #tells the respond type to the client
print """<html><head><title>FooBarBaz</title></head>
<body>Hello world!</body>
</html>
"""