// Point2.java

import java.sql.SQLException;
import oracle.jdbc.driver.OracleConnection;
import oracle.sql.STRUCT;
import oracle.sql.Datum;
import oracle.sql.CustomDatum;
import oracle.sql.CustomDatumFactory;
import oracle.sql.StructDescriptor;

public class Point2 implements CustomDatum
{
  double x;
  double y;

  public static CustomDatumFactory getFactory () {
    return new Point2Factory();
  }

  public Point2 (STRUCT s) throws SQLException {
    Datum[] attributes = s.getOracleAttributes ();
    x = attributes[0].doubleValue();
    y = attributes[1].doubleValue();
  }

  public Datum toDatum (OracleConnection conn) throws SQLException {
    StructDescriptor sd =
      StructDescriptor.createDescriptor ("SCOTT.POINT", conn);
    Object [] attributes = { new Double (x), new Double (y) };
    STRUCT struct = new STRUCT (sd, conn, attributes);
    return struct;
  }

  public double distance (Point2 p) {
    return Math.sqrt ((y - p.y) * (y - p.y) + (x - p.x) * (x - p.x));
  }

  public void moveBy (Point2 p) {
    x += p.x;
    y += p.y;
  }
}

class Point2Factory implements CustomDatumFactory
{
  public CustomDatum create (Datum d, int sqlType) throws SQLException {
    if (d == null) return null;
    return new Point2 ((STRUCT)d);
  }
}
