/*
_____       _    _    Corso   Italia,  178
(_|__   .  (_   |_|_  56125           Pisa
(_|_) |)|(()_)()| |   tel.  +39  050 46380
  |   |               picosoft@picosoft.it

 Copyright (C) Picosoft s.r.l. 1995-2002

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2, or (at your option)
 any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/
package IT.picosoft.jdbc;
class IOR {
   private static String intToHex(int number, int bytes) {
      String result = Integer.toHexString(number).toUpperCase();
      while (result.length() < 2 * bytes)
         result = "0" + result;
      return result;
   }
   private static String charToHexString(char c) {
      return Integer.toHexString((int)c).toUpperCase();
   }
   private static String stringToHexString(String s) {
      String hexString = "";
      for (int c = 0; c < s.length(); hexString += charToHexString(s.charAt(c++)));
      return hexString + "00";
   }
   private String ior = "";
   public IOR(String id, String host, int port, String key) {
      buildHead(id);
      buildProfile(host, port, key);
      ior = "IOR:" + ior;
   }
   private void addPad(int bytes) {
      while (ior.length() % (2 * bytes) > 0)
         ior += "00";
   }
   private void addInt(int number, int bytes) {
      addPad(bytes);
      ior += intToHex(number, bytes);
   }
   private void addString(String s) {
      addInt(s.length() + 1, 4);
      ior += stringToHexString(s);
   }
   private void buildHead(String id) {
      addInt(0, 1); //ENDIAN
      addString(id); //ID
      addInt(1, 4);//NUMERO PROFILI
   }
   private void buildProfile(String host, int port, String key) {
      addInt(0, 4);//PROTOCOLLO
      int l = ior.length();
      addInt(0, 1);//ENDIAN
      addInt(1, 1);//MAJOR
      addInt(0, 1);//MINOR
      addString(host);//HOST
      addInt(port, 2);//PORT
      addString(key);//KEY
      ior = ior.substring(0, l) + intToHex((ior.length() - l) / 2, 4) + ior.substring(l);
   }
   public String toString() {return ior;}
}
