import java.rmi.*;
import java.rmi.server.*;
import java.math.*;
import java.net.MalformedURLException;

import gov.nih.nlm.kss.api.*;
import gov.nih.nlm.kss.models.meta.concept.*;
import gov.nih.nlm.kss.models.meta.assocExp.*;
import gov.nih.nlm.kss.models.meta.relation.*;
import gov.nih.nlm.kss.models.meta.context.*;
import gov.nih.nlm.kss.models.meta.cooccurrence.*;
import gov.nih.nlm.kss.models.meta.attribute.*;
import gov.nih.nlm.kss.util.DatabaseException;

import java.util.*;
import java.io.*;

import iotools.*;

public class ExpertClientUMLS
{
  public ExpertClientUMLS() throws Exception
  {
    try
    {
      Configuration config = new Configuration();
      String dbYear        = config.umls_dbYear();
      String language      = config.umls_language();
      String host          = config.umls_host();
      String name          = "//" + host + "/KSSRetriever";

      String path         = config.path() + "\\tmp\\";
      String xmlQueryFile = path + config.tmp_UMLS();
      String xmlTermFile  = path + config.tmp_terms();

      KSSRetrieverV2_1 retriever = null;
      String xmlQuery = null;

      BufferedReader br = new BufferedReader(new FileReader(xmlQueryFile));
      StringBuffer xml = new StringBuffer(50000);

      // --- read each line from the XML file and add it to the buffer
      String s = "";
      while (s != null)
      {
        s = br.readLine();
        if (s != null) xml.append(s);
      }

      xmlQuery = xml.toString();

      retriever = (KSSRetrieverV2_1) Naming.lookup(name);

      // --- execute the requested query and print out the resulting XML returned
      char[] result = retriever.query(dbYear, xmlQuery);

      if (result == null) {System.out.println("UMLS query returned no results!"); return;}

      String xmlResult = new String(result);
      FileWriter terms_out = new FileWriter(xmlTermFile);
      terms_out.write(xmlResult);
      terms_out.close();

      // --- to help with garbage collection, the retriever is set to null here
      retriever = null;
    }
    catch (Exception ex) {ex.printStackTrace();}
  }
}

