Package center.task.api.db

Source Code of center.task.api.db.TaskAPI$LogInfo

package center.task.api.db;

import ru.vassaev.core.Expression;
import ru.vassaev.core.Pool;
import ru.vassaev.core.util.Strings;
import ru.vassaev.core.exception.SysException;
import ru.vassaev.core.thread.*;
import ru.vassaev.core.thread.Process;
import ru.vassaev.core.io.OutputByteBuffer;
import ru.vassaev.core.base.Null;
import ru.vassaev.core.container.ApplicationManager;
import ru.vassaev.core.db.IDBHelper;
import ru.vassaev.core.db.Manager;
import ru.vassaev.core.db.Sttmnt;

import java.io.*;

import center.system.DNF;
import center.task.Record;
import center.task.State;
import center.task.TypeOfState;
import center.task.api.ATaskAPI;
import center.task.api.ITaskAPI;
import center.task.api.TaskCI;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.LinkedList;

import center.db.*;
import org.w3c.dom.Node;

public final class TaskAPI extends ATaskAPI {
  private static Map<String, ITaskAPI> helpers = new TreeMap<String, ITaskAPI>();
  private final String alias;
  private final ru.vassaev.core.db.Types tp;
  private final IDBHelper dbh;

  public String getAlias() {
    return alias;
  }

  private TaskAPI(String alias) throws SysException {
    // Проверка возможности соединения
    Connection con = Manager.getConnection(alias);
    tp = Manager.getTypes(con);
    dbh = tp.getDBHelper();
    Manager.freeConnection(con);
    this.alias = alias;
  }

  public static ITaskAPI getInstance(String dbAlias) throws SysException {
    synchronized (helpers) {
      ITaskAPI obj = helpers.get(dbAlias);
      if (obj != null) {
        return obj;
      } else {
        TaskAPI o = new TaskAPI(dbAlias);
        helpers.put(dbAlias, o);
        return o;
      }
    }
  }

  private long getSeq(String name) throws SysException {
    Connection con = Manager.getConnection(alias);
    try {
      PreparedStatement pst;
      long id = 0;
      int attempt = 2;
      while (true)
        try {
          pst = con.prepareStatement(dbh.getSQLSeqNext(name));
          try {
            ResultSet rs = pst.executeQuery();
            if (rs.next())
              id = rs.getLong(1);
            rs.close();
          } finally {
            pst.close();
          }
          return id;
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        }
    } catch (Exception ex) {
      throw new SysException(ex);
    } finally {
      Manager.freeConnection(con);
    }
  }

  public long getSubject(long old_subject_id) throws SysException {
    if (old_subject_id > 0)
      return old_subject_id;
    return getSeq("seq_subject");
  }

  public long createTask(long subject_id, String cls) throws SysException {
    long id = getSeq("seq_tasks");
    String dtf = dbh.getSQLFuncNow();
    PreparedStatement pst;
    String sql = "insert into tasks(id, dt_created\n" + ", status_id \n"
        + ", classname, initiator_id) \n" + // , initiator_id
        "values(?, " + dtf + "\n" + ", 'CREATED', ?, ?) \n";
    Connection con = Manager.getConnection(alias);
    try {
      int attempt = 2;
      while (true)
        try {
          pst = con.prepareStatement(sql);
          pst.setLong(1, id);
          pst.setString(2, cls);
          pst.setLong(3, subject_id);
          try {
            pst.execute();
            Manager.commit(con);
          } finally {
            pst.close();
          }
          return id;
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        }
    } finally {
      Manager.freeConnection(con);
    }
  }

  public long createTask(long subject_id, String cls, long parent_task_id)
      throws SysException {
    long id = getSeq("seq_tasks");
    String dtf = dbh.getSQLFuncNow();
    PreparedStatement pst;
    String sql = "insert into tasks(id, dt_created\n" + ", status_id \n"
        + ", classname, initiator_id, parent_id) \n" + // , initiator_id
        "values(?, " + dtf + "\n" + ", 'CREATED', ?, ?, ?) \n";
    Connection con = Manager.getConnection(alias);
    try {
      int attempt = 2;
      while (true)
        try {
          pst = con.prepareStatement(sql);
          pst.setLong(1, id);
          pst.setString(2, cls);
          pst.setLong(3, subject_id);
          pst.setLong(4, parent_task_id);
          try {
            pst.execute();
            Manager.commit(con);
          } finally {
            pst.close();
          }
          return id;
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        }
    } finally {
      Manager.freeConnection(con);
    }
  }

  private StatementNew stmtGetNow = new StatementNew();

  public Timestamp getNow() throws SysException {
    Connection con = Manager.getConnection(alias);
    try {
      return getNow(con);
    } finally {
      Manager.freeConnection(con);
    }
  }

  public Timestamp getNow(Connection con) throws SysException {
    synchronized(stmtGetNow) {
      if (stmtGetNow.isClosed())
        stmtGetNow.prepare(alias, "select " + dbh.getSQLFuncNow()
          + " from dual");
    }
    try {
      Timestamp tm = null;

      PreparedStatement now = stmtGetNow.getStatement(con);
      try {
        ResultSet rs = now.executeQuery();
        if (rs.next()) {
          tm = rs.getTimestamp(1);
        }
        rs.close();
      } finally {
        stmtGetNow.freeStatement(now);
      }
      return tm;
    } catch (SQLException ex) {
      throw new SysException(ex);
    } catch (Exception ex) {
      throw new SysException(ex);
    }
  }

  public long setTaskDT(long id, String dt, String duration,
      String block_duration, Double arch_day) throws SysException {
    PreparedStatement pst;
    String dur = (duration == null || duration.trim().length() == 0) ? "120"
        : duration;
    String bldur = (block_duration == null || block_duration.trim().length() == 0) ? "10"
        : block_duration;
    String sql = "update tasks set dt_goal = ("
        + ((dt == null || dt.trim().length() == 0) ? dbh.getSQLFuncNow() : dt)
        + "), finish_duration = (" + dur + "), block_duration = (" + bldur
        + "), arch_day = nvl(?, arch_day) where id = ? and status_id = 'CREATED'";
    int attempt = 2;
    Connection con = Manager.getConnection(alias);
    try {
      while (true)
        try {
          pst = con.prepareStatement(sql);
          try {
            if (arch_day == null)
              pst.setNull(1, java.sql.Types.DOUBLE);
            else
              pst.setDouble(1, arch_day);
            pst.setLong(2, id);
            pst.executeUpdate();
          } finally {
            pst.close();
          }

          Manager.commit(con);
          break;
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        }

      long tm = 0;
      sql = "select u.dt_goal from tasks u \n" + "where u.id=?";

      attempt = 2;
      while (true)
        try {
          pst = con.prepareStatement(sql);
          try {
            pst.setLong(1, id);
            ResultSet rs = pst.executeQuery();
            if (rs.next())
              tm = rs.getTimestamp(1).getTime();
            rs.close();
          } finally {
            pst.close();
          }
          return tm;
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        }
    } finally {
      Manager.freeConnection(con);
    }
  }

  public Sttmnt stmtSTPO = new Sttmnt();

  public long setParamObject(long task_id, String name, Object value,
      long wait, long calc, long sc) throws SysException {
    synchronized(stmtSTPO) {
      if (stmtSTPO.isClosed()) {
        String sql;
        if (tp.getBaseVendorName().equals("FIREBIRD")) {
          sql = "<sql>{<o>id</o> = call set_param "
              + "\n<p>task_id</p>, <p>grp</p>, <p>name</p>, "
              + "\n<p>value</p>, <p>value_clob</p>, <p>value_blob</p>, "
              + "\n<p>value_clmn</p>, <p>len</p>, <p>tp</p>, <p>wait</p>, <p>calc</p>, <p>sc</p> }</sql>";
        } else {
          sql = "<sql>begin\n"
              + "\t<o>id</o> := set_param("
              + "<p>task_id</p>, <p>grp</p>, <p>name</p>, "
              + "<p>value</p>, <p>value_clob</p>, <p>value_blob</p>, "
              + "<p>value_clmn</p>, <p>len</p>, <p>tp</p>, <p>wait</p>, <p>calc</p>, <p>sc</p>);\n"
              + "end;</sql>";
        }
        stmtSTPO.setSQLExpression(sql, "i", "p", "o");
        stmtSTPO.prepare(alias);
        //System.out.println(stmtSTPO.getSQLExpression());
      }
    }
    Connection con = Manager.getConnection(alias);
    Object val = value;
    if (val instanceof Record) {
      Record r = (Record)val;
      if (r.size() > 0)
        val = r.getObject(0);
    }
    /*
    try {
      PreparedStatement st = con.prepareStatement("select * from params");
      ResultSetMetaData rs = st.getMetaData();
      for(int i = 1; i < rs.getColumnCount(); i++) {
        System.out.println(rs.getColumnType(i) + " = " +
        rs.getColumnName(i));
      }
      st.close();
    } catch(Exception e) {
     
    }//*/
    int attempt = 2;
    try {
      while (true)
        try {
          String[] fn = getName(name);
          CallableStatement st = stmtSTPO.getCallStatement(con);
          stmtSTPO.setParam(st, "task_id", task_id, java.sql.Types.BIGINT);
          stmtSTPO.setParam(st, "grp", fn[0], java.sql.Types.VARCHAR);
          stmtSTPO.setParam(st, "name", fn[1], java.sql.Types.VARCHAR);
          stmtSTPO.setParam(st, "wait", wait, java.sql.Types.BIGINT);
          stmtSTPO.setParam(st, "calc", calc, java.sql.Types.BIGINT);
          stmtSTPO.setParam(st, "sc", sc, java.sql.Types.BIGINT);
          if (Null.equ(val)) {
            stmtSTPO.setParam(st, "value_clmn", "VALUE", java.sql.Types.VARCHAR);
            stmtSTPO.setParam(st, "value", null, java.sql.Types.VARCHAR);
            stmtSTPO.setParam(st, "value_blob", null, java.sql.Types.BLOB);
            stmtSTPO.setParam(st, "value_clob", null, java.sql.Types.CLOB);
            stmtSTPO.setParam(st, "len", 0, java.sql.Types.BIGINT);
            stmtSTPO.setParam(st, "tp", null, java.sql.Types.VARCHAR);
          } else {
           
            stmtSTPO.setParam(st, "tp", val.getClass().getCanonicalName(),
                java.sql.Types.VARCHAR);
            if (val instanceof Node) {
              Node node = (Node) val;
              stmtSTPO.setParam(st, "value_clmn", "VALUE_BLOB", java.sql.Types.VARCHAR);
              stmtSTPO.setParam(st, "value", null, java.sql.Types.VARCHAR);
              Blob blob = tp.writeBlob(con, node, "utf-8");
              stmtSTPO.setParam(st, "value_blob", blob, java.sql.Types.BLOB);
              stmtSTPO.setParam(st, "value_clob", null, java.sql.Types.CLOB);
              stmtSTPO.setParam(st, "len", blob.length(), java.sql.Types.BIGINT);
            } else if (val instanceof Reader) {
              Reader rd = (Reader) val;
              stmtSTPO.setParam(st, "value_clmn", "VALUE_BLOB", java.sql.Types.VARCHAR);
              stmtSTPO.setParam(st, "value", null, java.sql.Types.VARCHAR);
              Blob blob = tp.writeBlob(con, rd, "utf-8");
              stmtSTPO.setParam(st, "value_blob", blob, java.sql.Types.BLOB);
              stmtSTPO.setParam(st, "value_clob", null, java.sql.Types.CLOB);
              stmtSTPO.setParam(st, "len", blob.length(), java.sql.Types.BIGINT);
            } else if (val instanceof OutputByteBuffer) {
              InputStream is = ((OutputByteBuffer) val).getIS();
              stmtSTPO.setParam(st, "value_clmn", "VALUE_BLOB", java.sql.Types.VARCHAR);
              stmtSTPO.setParam(st, "value", null, java.sql.Types.VARCHAR);
              Blob blob = tp.writeBlob(con, is);
              stmtSTPO.setParam(st, "value_blob", blob, java.sql.Types.BLOB);
              stmtSTPO.setParam(st, "value_clob", null, java.sql.Types.CLOB);
              stmtSTPO.setParam(st, "len", blob.length(), java.sql.Types.BIGINT);
              is.close();
            } else if (val instanceof byte[]) {
              OutputByteBuffer buf = new OutputByteBuffer(((byte[]) val).length);
              buf.write((byte[])val);
              buf.close();
              InputStream is = buf.getIS();
              stmtSTPO.setParam(st, "value_clmn", "VALUE_BLOB", java.sql.Types.VARCHAR);
              stmtSTPO.setParam(st, "value", null, java.sql.Types.VARCHAR);
              Blob blob = tp.writeBlob(con, is);
              stmtSTPO.setParam(st, "value_blob", blob, java.sql.Types.BLOB);
              stmtSTPO.setParam(st, "value_clob", null, java.sql.Types.CLOB);
              stmtSTPO.setParam(st, "len", blob.length(), java.sql.Types.BIGINT);
              is.close();
            } else if (val instanceof InputStream) {
              InputStream is = (InputStream) val;
              stmtSTPO.setParam(st, "value_clmn", "VALUE_BLOB", java.sql.Types.VARCHAR);
              stmtSTPO.setParam(st, "value", null, java.sql.Types.VARCHAR);
              Blob blob = tp.writeBlob(con, is);
              stmtSTPO.setParam(st, "value_blob", blob, java.sql.Types.BLOB);
              stmtSTPO.setParam(st, "value_clob", null, java.sql.Types.CLOB);
              stmtSTPO.setParam(st, "len", blob.length(), java.sql.Types.BIGINT);
            } else if (val instanceof File) {
              File file = (File) val;
              stmtSTPO.setParam(st, "value_clmn", "FILE", java.sql.Types.VARCHAR);
              stmtSTPO.setParam(st, "value", file.getCanonicalPath(), java.sql.Types.VARCHAR);
              //Blob blob = tp.writeBlob(con, file);
              stmtSTPO.setParam(st, "value_blob", null, java.sql.Types.BLOB);
              stmtSTPO.setParam(st, "value_clob", null, java.sql.Types.CLOB);
              stmtSTPO.setParam(st, "len", file.length(), java.sql.Types.BIGINT);
            } else if (val instanceof Blob) {
              stmtSTPO.setParam(st, "value_clmn", "VALUE_BLOB", java.sql.Types.VARCHAR);
              stmtSTPO.setParam(st, "value", null, java.sql.Types.VARCHAR);
              Blob blob = (Blob) val;
              stmtSTPO.setParam(st, "value_blob", blob, java.sql.Types.BLOB);
              stmtSTPO.setParam(st, "value_clob", null, java.sql.Types.CLOB);
              stmtSTPO.setParam(st, "len", blob.length(), java.sql.Types.BIGINT);
            } else if (val instanceof Clob) {
              stmtSTPO.setParam(st, "value_clmn", "VALUE_CLOB", java.sql.Types.VARCHAR);
              stmtSTPO.setParam(st, "value", null, java.sql.Types.VARCHAR);
              Clob clob = (Clob) val;
              stmtSTPO.setParam(st, "value_blob", null, java.sql.Types.BLOB);
              stmtSTPO.setParam(st, "value_clob", clob, java.sql.Types.CLOB);
              stmtSTPO.setParam(st, "len", clob.length(), java.sql.Types.BIGINT);
            } else {
              String str = Strings.getString(val);
              if (str == null) {
                stmtSTPO.setParam(st, "value_clmn", "VALUE", java.sql.Types.VARCHAR);
                stmtSTPO.setParam(st, "value", null, java.sql.Types.VARCHAR);
                stmtSTPO.setParam(st, "value_blob", null, java.sql.Types.BLOB);
                stmtSTPO.setParam(st, "value_clob", null, java.sql.Types.CLOB);
                stmtSTPO.setParam(st, "len", 0, java.sql.Types.BIGINT);
                stmtSTPO.setParam(st, "tp", null, java.sql.Types.VARCHAR);
              } else {
                long len = str.length();
                if (len > 2000) {
                  stmtSTPO.setParam(st, "value_clmn", "VALUE_CLOB", java.sql.Types.VARCHAR);
                  stmtSTPO.setParam(st, "value", str.substring(0, 2000), java.sql.Types.VARCHAR);
                  Clob clob = tp.writeClob(con, str);
                  stmtSTPO.setParam(st, "value_clob", clob, java.sql.Types.CLOB);
                } else {
                  stmtSTPO.setParam(st, "value_clmn", "VALUE", java.sql.Types.VARCHAR);
                  stmtSTPO.setParam(st, "value", str, java.sql.Types.VARCHAR);
                  stmtSTPO.setParam(st, "value_clob", null, java.sql.Types.CLOB);
                }
                stmtSTPO.setParam(st, "value_blob", null, java.sql.Types.BLOB);
                stmtSTPO.setParam(st, "len", len, java.sql.Types.BIGINT);
              }
            }
          }
          //st.registerOutParameter(1, java.sql.Types.BIGINT);
          st.execute();
          Object o = stmtSTPO.getParam(st, "id");
          Manager.commit(con);

          return Strings.parseIntegerNvl(o, 0);
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        }
    } finally {
      Manager.freeConnection(con);
    }
  }

  public long getParamId(long id_task, String[] fn, Connection con)
      throws SQLException {
    PreparedStatement fnd;
    if (fn[0] == null) {
      if (fn[1] == null) {
        fnd = con.prepareStatement("select id\n"
            + " from params where task_id=? and name is null and grp is null");
        fnd.setLong(1, id_task);
      } else {
        fnd = con.prepareStatement("select id\n"
            + " from params where task_id=? and name=? and grp is null");
        fnd.setLong(1, id_task);
        fnd.setString(2, fn[1]);
      }
    } else {
      if (fn[1] == null) {
        fnd = con.prepareStatement("select id\n"
            + " from params where task_id=? and name is null and grp=?");
        fnd.setLong(1, id_task);
        fnd.setString(2, fn[0]);
      } else {
        fnd = con.prepareStatement("select id\n"
            + " from params where task_id=? and name=? and grp=?");
        fnd.setLong(1, id_task);
        fnd.setString(2, fn[1]);
        fnd.setString(3, fn[0]);
      }
    }
    long id_param = 0;
    try {
      ResultSet rs = fnd.executeQuery();
      if (rs.next()) {
        id_param = rs.getLong(1);
      }
      rs.close();
      fnd.clearWarnings();
    } finally {
      fnd.close();
    }
    return id_param;
  }

  public PreparedStatement getParamValue(long id_task, String[] fn,
      Connection con) throws SQLException {
    PreparedStatement fnd;
    if (fn[0] == null) {
      if (fn[1] == null) {
        fnd = con.prepareStatement("select *\n"
            + " from params where task_id=? and name is null and grp is null");
        fnd.setLong(1, id_task);
      } else {
        fnd = con.prepareStatement("select *\n"
            + " from params where task_id=? and name=? and grp is null");
        fnd.setLong(1, id_task);
        fnd.setString(2, fn[1]);
      }
    } else {
      if (fn[1] == null) {
        fnd = con.prepareStatement("select *\n"
            + " from params where task_id=? and name is null and grp=?");
        fnd.setLong(1, id_task);
        fnd.setString(2, fn[0]);
      } else {
        fnd = con.prepareStatement("select *\n"
            + " from params where task_id=? and name=? and grp=?");
        fnd.setLong(1, id_task);
        fnd.setString(2, fn[1]);
        fnd.setString(3, fn[0]);
      }
    }
    return fnd;
  }

  public long setTaskError(long id, Throwable e) throws SysException {
    PreparedStatement pst;
    String sql = "update tasks set errs = ?, errp = ? where id = ?";
    int attempt = 2;
    Connection con = Manager.getConnection(alias);
    try {
      while (true)
        try {
          pst = con.prepareStatement(sql);
          if (e != null) {
            pst.setString(1, e.getMessage());
            //CLOB clob = CLOB.createTemporary(con, true, CLOB.DURATION_SESSION);
            //Writer out = clob.getCharacterOutputStream();
            //PrintWriter pw = new PrintWriter(out);
            e.printStackTrace();
            Clob clob;
            try {
              clob = tp.writeClob(con, e);
            } catch (IOException e1) {
              throw new SQLException(e1);
            }
            pst.setClob(2, clob);
          } else {
            pst.setNull(1, Types.VARCHAR);
            pst.setNull(2, Types.CLOB);
          }
          pst.setLong(3, id);
          try {
            pst.executeUpdate();
          } finally {
            pst.close();
          }

          Manager.commit(con);
          return id;
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        }
    } finally {
      Manager.freeConnection(con);
    }
  }

  public String getParamTask(long id, String name) throws SysException {
    Connection con = Manager.getConnection(alias);
    int attempt = 2;
    try {
      while (true)
        try {
          PreparedStatement fnd = con.prepareStatement("SELECT " + name + "\n"
              + "FROM tasks where tasks.id=?");
          fnd.setLong(1, id);
          String val = "";
          try {
            ResultSet rs = fnd.executeQuery();
            if (rs.next()) {
              val = rs.getString(1);
            }
            rs.close();
          } finally {
            fnd.close();
          }
          return val;
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        }
    } finally {
      Manager.freeConnection(con);
    }
  }

  public State getState(long id) throws SysException {
    Connection con = Manager.getConnection(alias);
    int attempt = 2;
    try {
      while (true)
        try {
          String state = State.UNKNOWN.name();
          PreparedStatement fnd = con.prepareStatement("SELECT status_id\n"
              + "FROM tasks where id=?");
          fnd.setLong(1, id);
          try {
            ResultSet rs = fnd.executeQuery();
            if (rs.next()) {
              state = rs.getString(1);
            }
            rs.close();
          } finally {
            fnd.close();
          }
          return State.valueOf(state);
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        }
    } finally {
      Manager.freeConnection(con);
    }
  }

  private StatementNew stmtGetTaskParams = new StatementNew();

  public String getClassName(long id) throws SysException {
    synchronized(stmtGetTaskParams) {
      if (stmtGetTaskParams.isClosed())
        stmtGetTaskParams.prepare(alias, "select * from tasks where id=::ID");
    }
    Connection con = Manager.getConnection(alias);
    int attempt = 2;
    try {
      while (true)
        try {
          String name = null;

          PreparedStatement fnd = stmtGetTaskParams.getStatement(con);
          try {
            stmtGetTaskParams.setParam(fnd, "ID", id, java.sql.Types.BIGINT);
            ResultSet rs = fnd.executeQuery();
            if (rs.next()) {
              name = rs.getString("CLASSNAME");
            }
            rs.close();
          } finally {
            stmtGetTaskParams.freeStatement(fnd);
          }
          return name;
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        }
    } finally {
      Manager.freeConnection(con);
    }
  }

  private long setStatusTemplate(long subject_id, long id, State to,
      Long processor_id) throws SysException {
    int attempt = 2;
    Connection con = Manager.getConnection(alias);
    try {
      while (true)
        try {
          int cnt = 0;
          State[] from = to.getFrom();
          StringBuffer sts = new StringBuffer();
          sts.append("update tasks u \n").append("set u.status_id=? \n");
          if (to.equals(State.READY)) {
            sts.append(", u.dt_goal=").append(dbh.getSQLFuncNow()).append("\n");
            if (processor_id != null)
              sts.append(", u.processor_id=").append(processor_id).append("\n");
          } else if (to.equals(State.PROCESSING)) {
            sts.append(", u.dt_started=").append(dbh.getSQLFuncNow()).append(
                "\n");
          } else if (to.equals(State.BLOCKED)) {
            sts.append(", u.processor_id=").append(subject_id).append("\n");
            sts.append(", u.program='JAVA'\n");
          } else if (to.getType().equals(TypeOfState.LAST)) {
            sts.append(", u.dt_finished=").append(dbh.getSQLFuncNow()).append(
                "\n");
          }
          sts.append("where u.id=? and \n").append("u.status_id in (?");
          for (int i = from.length - 1; i > 0; i--) {
            sts.append(",?");
          }
          sts.append(")");
          String sql = sts.toString();

          PreparedStatement pst;
          pst = con.prepareStatement(sql);
          try {
            pst.setString(1, to.name());
            pst.setLong(2, id);
            for (int i = from.length - 1; i >= 0; i--) {
              pst.setString(i + 3, from[i].name());
            }
            cnt = pst.executeUpdate();
          } finally {
            pst.close();
          }
          Manager.commit(con);
          if (cnt == 1)
            return id;
          return 0L;
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        }
    } finally {
      Manager.freeConnection(con);
    }
  }

  public long setBlocked(long subject_id, long id) throws SysException {
    Connection con = Manager.getConnection(alias);
    long id_task = id;
    PreparedStatement pst;
    String sql = "update tasks u \n" + "set u.status_id='BLOCKED', \n"
        + "u.program='JAVA', \n" + "u.processor_id=? \n"
        + "where u.id=? and \n" + "u.status_id='READY'";
    int attempt = 2;
    try {
      while (true)
        try {

          pst = con.prepareStatement(sql);
          pst.setLong(1, subject_id);
          pst.setLong(2, id);
          try {
            pst.executeUpdate();
          } finally {
            pst.close();
          }

          Manager.commit(con);
          break;
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        }

      sql = "select u.id from tasks u \n" + "where u.id=? and \n"
          + "u.processor_id=?";
      attempt = 2;
      while (true)
        try {
          pst = con.prepareStatement(sql);
          pst.setLong(1, id);
          pst.setLong(2, subject_id);
          try {
            ResultSet rs = pst.executeQuery();
            if (rs.next()) {
              id_task = id;
            } else {
              id_task = 0L;
            }
            rs.close();
          } finally {
            pst.close();
          }
          break;
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        }
      return id_task;
    } catch (SysException ex) {
      throw ex;
    } finally {
      Manager.freeConnection(con);
    }
  }

  public long setReady(long subject_id, long id, Long processor_id)
      throws SysException {
    long id_task = setStatusTemplate(subject_id, id, State.READY, processor_id);
    log(subject_id, id, "set Status=READY");
    return id_task;
  }

  public long setProcessing(long subject_id, long id) throws SysException {
    return setStatusTemplate(subject_id, id, State.PROCESSING, null);
  }

  public long setTimeout(long subject_id, long id) throws SysException {
    return setStatusTemplate(subject_id, id, State.DONE_TOUT, null);
  }

  public long setScheduled(long subject_id, long id) throws SysException {
    return setStatusTemplate(subject_id, id, State.SCHEDULED, null);
  }

  public long setBreaking(long subject_id, long id) throws SysException {
    return setStatusTemplate(subject_id, id, State.BREAKING, null);
  }

  public long setBroken(long subject_id, long id) throws SysException {
    return setStatusTemplate(subject_id, id, State.BROKEN, null);
  }

  public long setCanceled(long subject_id, long id) throws SysException {
    return setStatusTemplate(subject_id, id, State.CANCELED, null);
  }

  public long setDoneErr(long subject_id, long id) throws SysException {
    return setStatusTemplate(subject_id, id, State.DONE_ERR, null);
  }

  public long setDoneOk(long subject_id, long id) throws SysException {
    return setStatusTemplate(subject_id, id, State.DONE_OK, null);
  }

  private StatementNew stmtLog = new StatementNew();

  private class LogInfo {
    String info;
    long subject_id;
    long id;
  }

  private ru.vassaev.core.thread.Process thg = new ru.vassaev.core.thread.Process();
  private ProcessLog prc = new ProcessLog();

  // Класс сборщика мусора
  private class ProcessLog implements Processed {
    // Просматриваемая очередь
    private LinkedList<LogInfo> lst = new LinkedList<LogInfo>();

    /**
     * Добавить нового кандидата
     *
     * @param candidate
     */
    public void addNewCandidate(LogInfo candidate) {
      synchronized (lst) {
        lst.addLast(candidate);
        lst.notify();
      }
    }

    public ProcessLog() {
      super();
    }

    /**
     * Выполняемый процесс по анализу потоков
     *
     * @throws InterruptedException
     */
    public void processing(Object prms) throws Throwable {
      while (true) {
        while (lst.size() > 0) {
          LogInfo o = null;
          synchronized (lst) {
            o = lst.removeFirst();
          }
          try {
            log0(o);
          } catch (SysException e) {
            e.printStackTrace(); // To change body of catch statement use File |
            // Settings | File Templates.
          }
        }
        synchronized (lst) {
          if (lst.size() == 0)
            lst.wait(1000);
        }
      }
    }

  }

  private long idx = 0;

  public long log0(LogInfo o) throws SysException {
    synchronized(stmtLog) {
      if (stmtLog.isClosed())
        stmtLog.prepare(alias,
            "insert into protocol (dt, task_id, text, subject_id, idx)\n"
                + "values (" + dbh.getSQLFuncNow() + ", ?, ?, ?, ?)");
    }
    Connection con = Manager.getConnection(alias);
    try {
      int trying = 2;
      int l = o.info.length();
      if (l > 4000)
        l = 4000;
      while (true) {
        PreparedStatement pst = stmtLog.getStatement(con);
        try {
          pst.setLong(1, o.id);
          if (o.info == null)
            pst.setNull(2, java.sql.Types.VARCHAR);
          else
            pst.setString(2, o.info.substring(0, l));
          pst.setLong(3, o.subject_id);
          pst.setLong(4, idx);
          idx++;
          pst.executeUpdate();
          Manager.commit(con);
          return o.id;
        } catch (SQLException ex) {
          ex.printStackTrace();
          trying--;
          if (trying > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        } finally {
          stmtLog.freeStatement(pst);
        }
      }
    } finally {
      Manager.freeConnection(con);
    }
  }

  private Object sync = new Object();

  public long log(long subject_id, long id, String info, boolean base) throws SysException {
    synchronized (sync) {
      System.out.println(this.alias + " : " + subject_id + " : " + id
          + " :\t" + info);
    }
    if (!base)
      return id;
    LogInfo o = new LogInfo();
    o.id = id;
    o.subject_id = subject_id;
    o.info = info;
    prc.addNewCandidate(o);
    synchronized (thg) {
      if (thg.canStart()) {
        thg.setTarget(prc);
        thg.start();
      }
    }
    return id;
  }
 
  public long log(long subject_id, long id, String info) throws SysException {
    synchronized (sync) {
      System.out.println(this.alias + " : " + subject_id + " : " + id
          + " :\t" + info);
    }
    LogInfo o = new LogInfo();
    o.id = id;
    o.subject_id = subject_id;
    o.info = info;
    prc.addNewCandidate(o);
    synchronized (thg) {
      if (thg.canStart()) {
        thg.setTarget(prc);
        thg.start();
      }
    }

    return id;
  }

  /**
   * Ожидание завершения задания
   *
   * @param subject_id
   *          long
   * @param id
   *          long
   * @param msec
   *          long - время ожидания в миллисекундах. Если < 0, то ожидание
   *          бесконечно.
   * @return State
   * @throws SysException
   */
  public State waitFinishedOld(long subject_id, long id, long msec)
      throws SysException {
    Connection con = null;
    try {
      con = Manager.getConnection(getAlias());
      CallableStatement st = con.prepareCall("begin"
          + "  ? := wait_for_end(?, ?);" + " end;");
      st.registerOutParameter(1, java.sql.Types.VARCHAR);

      st.setLong(2, id);
      st.setLong(3, msec);

      st.execute();
      String name = st.getString(1);
      st.close();
      return (name == null) ? null : State.valueOf(name);
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      Manager.freeConnection(con);
    }
    return null;
  }
 
  private Sttmnt stmtWait = new Sttmnt();
  public State waitFinished(long subject_id, long id, long msec) throws SysException {
    synchronized(stmtWait) {
      if (stmtWait.isClosed()) {
        stmtWait.setSQLExpression("<sql>begin <o type=\"VARCHAR\">st</o> := wait_for_end(<b>id</b>, <b>msec</b>); end;</sql>", "i", "b", "o");
        stmtWait.setParam("st", null, java.sql.Types.VARCHAR);
        stmtWait.prepare(this.alias);
      }
    }
    Connection con = Manager.getConnection(alias);
    try {
      int trying = 2;
      while (true) {
        CallableStatement pst = stmtWait.getCallStatement(con);
        try {
          pst.setLong(2, id);
          pst.setLong(3, msec/1000);

          pst.execute();
          String name = pst.getString(1);
          pst.close();
          return (name == null) ? null : State.valueOf(name);
        } catch (SQLException ex) {
          ex.printStackTrace();
          trying--;
          if (trying > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        } finally {
          stmtWait.freeStatement(pst);
        }
      }
    } finally {
      Manager.freeConnection(con);
    }
  }

  private StatementNew stmtSetBlocked = new StatementNew();

  private long setBlockedBySelect(long subject_id,
      StatementNew stmtListForBlocked) throws SysException {
    synchronized(stmtSetBlocked) {
      if (stmtSetBlocked.isClosed())
        stmtSetBlocked.prepare(alias, "update tasks\n"
            + "set status_id='BLOCKED'\n" + "   , program = 'JAVA'\n"
            + "   , processor_id=::SUBJECT_ID\n" + "where id=::ID\n"
            + "   and status_id=::STATUS_ID\n"
            + "   and processor_id=::PROCESSOR_ID");
      stmtSetBlocked.setParam("SUBJECT_ID", subject_id, java.sql.Types.BIGINT);
    }
    Connection con = Manager.getConnection(alias);
    int attempt = 2;
    try {
      while (true) {
        PreparedStatement pst = null;
        PreparedStatement st = null;
        try {
          pst = stmtListForBlocked.getStatement(con);
          st = stmtSetBlocked.getStatement(con);
          ResultSet rs = pst.executeQuery();
          while (rs.next()) {
            long id = rs.getLong(1);
            String status_id = rs.getString(2);
            int processor_id = rs.getInt(3);
            st.setLong(2, id);
            st.setString(3, status_id);
            st.setLong(4, processor_id);
            if (st.executeUpdate() == 1) {
              Manager.commit(con);
              return id;
            }
          }
          return 0;
        } catch (SysException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } finally {
          if (st != null)
            stmtSetBlocked.freeStatement(st);
          if (pst != null)
            stmtListForBlocked.freeStatement(pst);
        }
      }
    } finally {
      Manager.freeConnection(con);
    }
  }

  private StatementNew stmtListForBlockedByClassName = new StatementNew();

  public long getBlockedByClassName(long subject_id, String cls)
      throws SysException {
    synchronized(stmtListForBlockedByClassName) {
    String dt = dbh.getSQLFuncNow();
    if (stmtListForBlockedByClassName.isClosed())
      stmtListForBlockedByClassName
          .prepare(
              alias,
              "select l.id, l.status_id, l.processor_id\n"
                  + "from tasks l\n"
                  + "where l.className=::CLASSNAME\n"
                  + "   and l.status_id=(select max(a.id) from status a where a.name='READY')\n"
                  + "   and " + dbh.getSQLFuncCastAs("l.dt", "date") + "<="
                  + dbh.getSQLFuncCastAs(dt, "date") + "\n" + "   and ("
                  + dbh.getSQLFuncCastAs("l.dt", "date") + ">"
                  + dbh.getSQLFuncCastAs(dt, "date")
                  + " - l.duration / (24.0*60.0*60.0)\n"
                  + "       or l.duration = 0)\n"
                  + "   and l.processor_id in (0, ::SUBJECT_ID)\n"
                  + "order by l.duration, l.dt, l.id");
    stmtListForBlockedByClassName.setParam("CLASSNAME", cls,
        java.sql.Types.VARCHAR);
    stmtListForBlockedByClassName.setParam("SUBJECT_ID", subject_id,
        java.sql.Types.BIGINT);
    return setBlockedBySelect(subject_id, stmtListForBlockedByClassName);
    }
  }

  private StatementNew stmtListForBlockedByGroupName = new StatementNew();

  private StatementNew stmtSetBlockedForProcessor = new StatementNew();
  private StatementNew stmtSelectResult = new StatementNew();
 
  public TaskCI getBlocked(long subject_id, long wait)
      throws SysException {
    TaskCI tci;
    if (tp.getBaseVendorName().equals("FIREBIRD")) {
      Object o = new Object();
      synchronized(o) {
        try {
          o.wait(1000);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        tci = new TaskCI();
        tci.id_task = 0;
      }
    } else {
      tci = getBlockedORACLE(subject_id, wait);
    }
    return tci;
  }
 
  private TaskCI getBlockedORACLE(long subject_id, long wait)
      throws SysException {
    TaskCI tci = new TaskCI();
    tci.id_task = 0;
    synchronized(stmtSetBlockedForProcessor) {
      if (stmtSetBlockedForProcessor.isClosed()) {
        stmtSetBlockedForProcessor
            .prepare(
                alias,
                "begin\n"
                    + "   ::RESULT := set_blocked('JAVA', ::SUBJECT_ID, ::WAIT, ::CLS);\n"
                    + "end;\n");
        stmtSelectResult.prepare(alias, "select value from params_");
      }
    }
    Connection con = Manager.getConnection(alias, false);
    int attempt = 2;
    try {
      while (true) {
        CallableStatement st = null;
        try {
          st = stmtSetBlockedForProcessor.getCallStatement(con);
          stmtSetBlockedForProcessor.setParam(st, "SUBJECT_ID", subject_id,
              java.sql.Types.BIGINT);
          stmtSetBlockedForProcessor.setParam(st, "WAIT", wait / 1000,
              java.sql.Types.NUMERIC);

          st.registerOutParameter(1, java.sql.Types.BIGINT);
          st.registerOutParameter(4, java.sql.Types.VARCHAR);

          st.executeUpdate();
          if (st.getObject(1) == null)
            return tci;
          tci.id_task = st.getLong(1);
          tci.cls_name = st.getString(4);
          return tci;
        } catch (SysException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (SQLException ex) {
          ex.printStackTrace();
          attempt--;
          if (attempt > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } finally {
          if (st != null) {
            stmtSetBlockedForProcessor.freeStatement(st);
          }
        }
      }
    } finally {
      Manager.freeConnection(con);
      if (tci.id_task > 0)
        log(subject_id, tci.id_task, "Blocked");
    }
  }
  @Deprecated
  public long getBlockedByGroupName(long subject_id, String grp)
      throws SysException {
    String dt = dbh.getSQLFuncNow();
    if (stmtListForBlockedByGroupName.isClosed())
      stmtListForBlockedByGroupName
          .prepare(
              alias,
              "select l.id, l.status_id, l.processor_id\n"
                  + "from tasks l inner join gc_links r on (l.classname=r.classname)\n"
                  + "where r.id_group in (select a.id from groups_list a where a.name=::GROUPNAME)\n"
                  + "   and l.status_id='READY'\n" + "   and "
                  + dbh.getSQLFuncCastAs("l.dt", "date") + "<="
                  + dbh.getSQLFuncCastAs(dt, "date") + "\n" + "   and ("
                  + dbh.getSQLFuncCastAs("l.dt", "date") + ">"
                  + dbh.getSQLFuncCastAs(dt, "date")
                  + " - l.block_duration / (24.0*60.0*60.0)\n"
                  + "       or l.duration = 0)\n"
                  + "   and l.processor_id in (0, ::SUBJECT_ID)\n"
                  + "order by l.block_duration, l.dt, l.id");
    stmtListForBlockedByGroupName.setParam("GROUPNAME", grp,
        java.sql.Types.VARCHAR);
    stmtListForBlockedByGroupName.setParam("SUBJECT_ID", subject_id,
        java.sql.Types.BIGINT);
    return setBlockedBySelect(subject_id, stmtListForBlockedByGroupName);
  }
/*
  public String getTaskParam(long id, String name) throws SysException {
    Connection con = Manager.getConnection(alias);
    try {
      int trying = 2;
      while (true)
        try {
          String result = null;
          String[] fn = getName(name);
          PreparedStatement fnd = getParamValue(id, fn, con);
          try {
            ResultSet rs = fnd.executeQuery();
            if (rs.next()) {
              result = rs.getString("VALUE");
              if (result == null)
                result = "";
            }
            rs.close();
          } finally {
            fnd.close();
          }
          return result;
        } catch (SQLException ex) {
          ex.printStackTrace();
          trying--;
          if (trying > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        }
    } finally {
      Manager.freeConnection(con);
    }
  }
//*/
 
  public Object readBlob(Blob a) throws SQLException, IOException {
    // File x = ru.vassaev.core.thread.Process.getTempFile("GROUP", ".BLOB");
    // FileOutputStream wr = new FileOutputStream(x);
    OutputByteBuffer wr = Process
        .getByteBuffer(8000);
    tp.readBlob(a, wr);
    // Object result = new FileInputStream(x);
    // ru.vassaev.core.thread.Process.registerResource(result);
    return wr;
  }

  public Map<String, Object> getGroupParams(long id, String group) throws SysException {
    Connection con = Manager.getConnection(alias);
    try {
      int trying = 2;
      while (true)
        try {
          PreparedStatement fnd = con.prepareStatement("select value_clmn"
              + ", \"VALUE\", value_clob, value_blob"
              + ", name, grp from params where task_id=?"
              + ((group != null) ? " and grp=?" : " and grp is null"));
          Map<String, Object> res = new HashMap<String, Object>();
          fnd.setLong(1, id);
          if (group != null)
            fnd.setString(2, group);
          try {
            ResultSet rs = fnd.executeQuery();
            while (rs.next()) {
              Object result = null;
              String k = rs.getString(1);
              if ("VALUE_BLOB".equalsIgnoreCase(k)) {
                Blob a = rs.getBlob(4);
                if (a != null) {
                  InputStream r = a.getBinaryStream();
                  //TODO Размер буфера надо сделать параметром
                  OutputByteBuffer wr = Process.getByteBuffer(8000);
                  byte[] buf = new byte[1024];
                  int l;
                  while ((l = r.read(buf)) > 0) {
                    wr.write(buf, 0, l);
                  }
                  wr.close();
                  r.close();
                  result = wr;
                  ru.vassaev.core.thread.Process.registerResource(wr);
                }
              } else if ("VALUE_CLOB".equalsIgnoreCase(k)) {
                Clob a = rs.getClob(3);
                if (a != null) {
                  Reader r = a.getCharacterStream();
                  OutputByteBuffer obb = Process.getByteBuffer(8000);// !!!
                  OutputStreamWriter wr = new OutputStreamWriter(obb, "utf-8");
                  char[] buf = new char[1024];
                  int l;
                  while ((l = r.read(buf)) > 0) {
                    wr.write(buf, 0, l);
                  }
                  result = obb;
                }
              } else {
                result = rs.getString(2);
              }
              if (result == null)
                result = Null.NULL;
              String fullname = getFullName(rs.getString(6), rs.getString(5));
              res.put(fullname, result);
            }
            rs.close();
          } finally {
            fnd.close();
          }
          return res;
        } catch (SQLException ex) {
          ex.printStackTrace();
          trying--;
          if (trying > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        }
    } finally {
      Manager.freeConnection(con);
    }
  }

  public Object getParam(long id, String name) throws SysException {
    Connection con = Manager.getConnection(alias);
    int trying = 2;
    try {
      while (true)
        try {
          Object result;
          String[] fn = getName(name);
          PreparedStatement fnd = getParamValue(id, fn, con);
          ResultSet rs = null;
          try {
            rs = fnd.executeQuery();
            if (!rs.next())
              break;
            String k = rs.getString("VALUE_CLMN");
            result = null;
            if ("VALUE_BLOB".equalsIgnoreCase(k)) {
              Blob a = rs.getBlob("VALUE_BLOB");
              if (a != null) {
                InputStream r = a.getBinaryStream();
                OutputByteBuffer wr = ru.vassaev.core.thread.Process
                    .getByteBuffer(8000);
                byte[] buf = new byte[1024];
                int l;
                while ((l = r.read(buf)) > 0) {
                  wr.write(buf, 0, l);
                }
                wr.close();
                r.close();
                result = wr;
                ru.vassaev.core.thread.Process.registerResource(result);
              }
              return result;
            }
            if ("VALUE_CLOB".equalsIgnoreCase(k)) {
              Clob a = rs.getClob("VALUE_CLOB");
              if (a != null) {
                Reader r = a.getCharacterStream();
                File x = ru.vassaev.core.thread.Process.getTempFile("GET",
                    ".CLOB");
                OutputStreamWriter wr = new OutputStreamWriter(
                    new FileOutputStream(x.getCanonicalPath()), "utf-8");
                char[] buf = new char[1024];
                int l;
                while ((l = r.read(buf)) > 0) {
                  wr.write(buf, 0, l);
                }
                wr.close();
                FileInputStream rd = new FileInputStream(x.getCanonicalPath());
                ru.vassaev.core.thread.Process.registerResource(rd);
                result = new InputStreamReader(rd, "utf-8");
              }
              return result;
            }
            if ("FILE".equalsIgnoreCase(k)) {
              return new File(rs.getString("VALUE"));
            }
            return rs.getString("VALUE");
          } finally {
            if (rs != null)
              rs.close();
            fnd.close();
          }
        } catch (SQLException ex) {
          ex.printStackTrace();
          trying--;
          if (trying > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        }
    } finally {
      Manager.freeConnection(con);
    }
    return null;
  }

  /*
  public Reader getTaskParamLong(long id, String name) throws SysException {
    Connection con = Manager.getConnection(alias);
    try {
      int trying = 2;
      while (true)
        try {
          String[] fn = getName(name);
          PreparedStatement fnd = getParamValue(id, fn, con);
          InputStreamReader rd = null;
          try {
            ResultSet rs = fnd.executeQuery();
            if (rs.next()) {
              Clob a = rs.getClob("VALUE_CLOB");
              if (a != null) {
                Reader r = a.getCharacterStream();
                File x = ru.vassaev.core.thread.Process.getTempFile("PRM",
                    ".CLOB");
                // File.createTempFile("clob", "dbxs");
                OutputStreamWriter wr = new OutputStreamWriter(
                    new FileOutputStream(x.getCanonicalPath()), "utf-8");
                char[] buf = new char[1024];
                int l = 0;
                while ((l = r.read(buf)) > 0) {
                  wr.write(buf, 0, l);
                }
                wr.close();
                FileInputStream rx = new FileInputStream(x.getCanonicalPath());
                ru.vassaev.core.thread.Process.registerResource(rx);
                rd = new InputStreamReader(rx, "utf-8");
              }
            }
            rs.close();
          } finally {
            fnd.close();
          }
          return rd;
        } catch (SQLException ex) {
          ex.printStackTrace();
          trying--;
          if (trying > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(ex);
        } catch (Exception ex) {
          throw new SysException(ex);
        }
    } finally {
      Manager.freeConnection(con);
    }
  }
  //*/
  /*
  public boolean checkDNF(long id, DNF dnf, Object[] flds) throws SysException {
    // if (flds.length == 0)
    // return false;
    StringBuffer s = new StringBuffer();
    s.append("select ");
    StringBuffer n = new StringBuffer();
    n.append("select ");

    StringBuffer fm = new StringBuffer();
    for (int i = 0; i < flds.length; i++) {
      String f = flds[i].toString();
      s.append("max(\"").append(f).append("\") \"").append(f).append("\", ");
      n.append("null ").append("\"").append(f).append("\", ");
    }
    s.append("1");
    n.append("1");
    fm.append("select * from (\n").append(s).append(" from (\n").append(n)
        .append(" from dual\n");
    // .append("union all\n")
    for (int i = 0; i < flds.length; i++) {
      String f = flds[i].toString();
      StringBuffer v = new StringBuffer();
      v.append("select ");
      for (int j = 0; j < i; j++) {
        v.append((j == 0) ? "" : ", ").append("null");
      }
      v.append((i == 0) ? "" : ", ").append("\"VALUE\" \"").append(f).append(
          "\"");
      for (int j = i + 1; j < flds.length; j++) {
        v.append(", ").append("null");
      }
      v.append(", null from params where task_id=").append(id).append(
          " and name='").append(f).append("\'\n");
      fm.append("union all\n").append(v);
    }
    fm.append(")\n)\nwhere ::E");

    Expression ex = new Expression(fm.toString(), "::");
    boolean b = false;
    {
      ex.setValue("E", dnf.toString());
      Connection con = Manager.getConnection(alias);
      try {
        int trying = 2;
        try {
          PreparedStatement fnd = con.prepareStatement(ex.toString());
          ResultSet rs = null;
          try {
            rs = fnd.executeQuery();
            b = rs.next();
            rs.close();
          } finally {
            fnd.close();
          }
        } catch (SQLException e) {
          e.printStackTrace();
          trying--;
          if (trying > 0) {
            con = Manager.reInitConnection(con);
          } else
            throw new SysException(e);
        }
      } finally {
        Manager.freeConnection(con);
      }
    }
    return b;
  }
  //*/
  public void writeLogToFile(long id, File file, String charset)
      throws SysException {
    Connection con = Manager.getConnection(alias);
    try {
      PreparedStatement fnd = con
          .prepareStatement("SELECT dt, text FROM protocol where task_id=? order by id");
      fnd.setLong(1, id);
      FileOutputStream wr = new FileOutputStream(file.getCanonicalPath());
      try {
        ResultSet rs = fnd.executeQuery();
        java.sql.Timestamp ts = new Timestamp(0);
        while (rs.next()) {
          Date dt = rs.getDate(1);
          String txt = rs.getString(2);
          if (dt != null) {
            ts.setTime(dt.getTime());
            wr.write(ts.toString().getBytes(charset));
          }
          wr.write("\t:\t".getBytes(charset));
          if (txt != null) {
            wr.write(txt.getBytes(charset));
          }
          wr.write("\n".getBytes(charset));
        }
        rs.close();
      } finally {
        fnd.close();
        wr.close();
      }
    } catch (Exception ex) {
      throw new SysException(ex);
    } finally {
      Manager.freeConnection(con);
    }
  }

  public void registerClasses(long subject_id, Set<String> hs) throws SysException {
    Pool<Connection> pool =
        (Pool<Connection>) ApplicationManager.getPoolByName(alias, Connection.class);
  //Pool<Connection>)ai.getContainer().getRM().getPool(dbAlias);
    Connection con = pool.occupyWait();
    try {
      PreparedStatement st = con
              .prepareStatement("insert into classes(processor_id, classname) "
                      + "values(?,?)");
     
      for (String s : hs) {
        st.setLong(1, subject_id);
        st.setString(2, s);
        st.execute();
        log(subject_id, 0, "Class by name " + s + " was added for searching");
      }
      con.commit();
      st.close();
    } catch (SQLException e1) {
      throw new SysException(e1);
    } finally {
      pool.free(con);
    }
  }

}
TOP

Related Classes of center.task.api.db.TaskAPI$LogInfo

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.
r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-20639858-1', 'auto'); ga('send', 'pageview');