Hi Miguel!
Miguel Arroz wrote:
I'm trying to define a Prototype to store an IP on a Postgres
database using the native inet type.
I tried first with toString and getByName, but I got an exception
that lead me to think that it's a binary format.
So, I did this:
...
And I got this:
...
Any ideias? Of course I could dump this to a varchar, but this
way it would be much cooler.
Unfortunately, you can't convert this "inet" datatype diretly to
"java.net.InetAddress" Java class, because the PostgreSQL datatype
holds the netmask as well, unlike the Java class (read this thread:
<http://osdir.com/ml/db.postgresql.jdbc/2003-12/msg00031.html>).
But you can create a custom class to manage this easily. For the
example below, you just have to bound factory method to "valueOf" and
conversion method to "toString":
package javax.net;
import java.net.InetAddress;
public class Inet extends Object {
private InetAddress _inetAddress;
private int _bitMask;
public Inet(InetAddress inetAddress, int bitMask) {
super();
if(inetAddress == null) {
throw new IllegalArgumentException("Inet adresse is
required.");
} // if
int maxBitMask = (inetAddress.getAddress().length * Byte.SIZE);
if((bitMask < 0) || (bitMask > maxBitMask)) {
throw new IllegalArgumentException(String.format("Bit mask can't
be below 0 nor above %d for %s address.", maxBitMask,
inetAddress.getHostAddress()));
} // if
_inetAddress = inetAddress;
_bitMask = bitMask;
} // Inet
public Integer bitMask() {
return _bitMask;
} // bitMask
public InetAddress inetAddress() {
return _inetAddress;
} // inetAddress
public static Inet valueOf(String string) {
Inet inet;
if(string != null) {
int bitMask, index;
InetAddress inetAddress;
try {
if((index = string.indexOf('/')) > -1) {
bitMask =
Integer.parseInt(string.substring(index + 1));
string = string.substring(0, index);
} else {
bitMask = 0;
} // else
inetAddress = InetAddress.getByName(string);
inet = new Inet(inetAddress, bitMask);
} catch(Exception exception) {
throw new IllegalArgumentException("Can't create valid inet
address and mask.", exception);
} // catch
} else {
inet = null;
} // else
return inet;
} // valueOf
public String toString() {
StringBuilder string;
string = new StringBuilder();
string.append(_inetAddress.getHostAddress());
string.append('/');
string.append(_bitMask);
return string.toString();
} // toString
} // Inet
Kind regards, and Boas Festas e um feliz Ano Novo!
Francis Labrie, Architecte de systèmes, OS communications
informatiques - Votre moteur de communication
[EMAIL PROTECTED] | Téléphone : (450) 676-1238, poste 27 | Télécopieur :
(450) 676-5276
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Webobjects-dev mailing list ([email protected])
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/webobjects-dev/archive%40mail-archive.com
This email sent to [EMAIL PROTECTED]