⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 magnitudetn.java

📁 一个用java写的地震分析软件(无源码)
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package org.trinet.jasi.TN;

import org.trinet.jasi.*;

import java.text.*;
import java.util.*;

import org.trinet.jasi.coda.*;
import org.trinet.jdbc.*;
import org.trinet.jdbc.table.NetMag;
import org.trinet.jdbc.datatypes.*;
import java.sql.*;
import org.trinet.jdbc.table.ExecuteSQL;
import org.trinet.jdbc.table.SeqIds;
import org.trinet.jdbc.table.DataTableRowStates;
/**
 *
 */

/**
 * Created: Wed Oct 29 10:35:35 1999
 *
 * @author Doug Given
 * @version
 *
 * Component of the Java Seismic Abstraction Layer.
 * This implementation interfaces
 * to the Berkeley/Caltech/USGS schema in Oracle. <p>
 * All data members are DataObjects rather than primative types so they can
 * handle the concept of "nullness". The database can contain null values for
 * certain fields. Also applications may not want to write a "bogus" value like 0
 * into the database when when the real value is not known. Data primatives can't
 * be null and are initiallize to zero.
 */

/*
  In the NCDC schema you would NEVER delete or update an existing 'NetMag' row.
  You would only create a new one and set 'prefmag' in Origin and Event to the
  new row.
 */
public class MagnitudeTN extends Magnitude {
    /*
      Here are protected data members used to support this particular
      implimentation of the abstract layer
     */

    // Schema classes that map to tables
    protected NetMag netMagRow;

    protected DataLong    commid = new DataLong();
    protected DataLong    orid   = new DataLong();

    /** True if this Solution was orginally read from the dbase. Used to know if
  a commit requires an 'insert' or an 'update' */
    boolean fromDbase = false;

    boolean debug = false;
    //    boolean debug = true;

    protected static PreparedStatement magPrefStatement = null;

    protected static PreparedStatement magPrioStatement = null;

    /**
     *  Create a Magnitude object.
     */
    public MagnitudeTN () {}
    /**
     * Returns the Magnitude for the event with this ID number from the data source.
     * Returns null if no mag is found.<p>
     * Uses the default DataSource.
     */
    protected static Magnitude getByMagId (long mgid)
    {
  return getByMagId(DataSource.getConnection(), mgid);
    }

    /**
     * Returns the Magnitude for the event with this MagId number from the
     * data source. Returns null if no mag is found.
     */
    protected static Magnitude getByMagId (Connection conn, long mgid)
    {
  Magnitude mag = Magnitude.create();

  try{
      if (conn.isClosed())	// check that valid connection exists
    {
        System.err.println ("* Connection is closed.");
        return null;
    }

      // Must do join to find prefor and prefmag of the given evid
      String sql = "Select netmag.* "+
    " from netmag " +
    " WHERE (netmag.magid = " + mgid +")" ;

      Statement sm = conn.createStatement();

      //	    System.out.println ("SQL: "+sql);

      ResultSetDb rsdb = new ResultSetDb(ExecuteSQL.rowQuery(sm, sql));

      if (rsdb == null) return null;	// nothing found

      // No next loop because there's only one
      if( !rsdb.getResultSet().next()) return null;	// empty resultset

      mag = parseResultSet(rsdb, 0);

      sm.close();
  }
  catch (SQLException ex) {
      System.err.println(ex);
      ex.printStackTrace();

  }

  return mag;

    }


    /**
     * Returns the Magnitude for the event with this ID number from the data source.
     * Returns null if no mag is found.<p>
     * Uses the default DataSource.
     */
    public Magnitude getBySolutionId (long id)
    {
  return getBySolutionId(DataSource.getConnection(), id);
    }

    /**
     * Returns the Magnitude for the event with this ID number from the data source.
     * Returns null if no mag is found.
     */
    public Magnitude getBySolutionId (Connection conn, long id)
    {

  Magnitude mag = Magnitude.create();

  try{
      if (conn.isClosed())	// check that valid connection exists
    {
        System.err.println ("* Connection is closed.");
        return null;
    }

      // Must do join to find prefor and prefmag of the given evid
      String sql = "Select "+NetMag.QUALIFIED_COLUMN_NAMES+
    " from event, origin, netmag " +
    " WHERE (event.prefor = origin.orid) and " +		    // join
    " (event.prefmag = netmag.magid) and "+
    " (event.evid = " + id +")" ;

      Statement sm = conn.createStatement();

      //	    System.out.println ("SQL: "+sql);

      ResultSetDb rsdb = new ResultSetDb(ExecuteSQL.rowQuery(sm, sql));

      if (rsdb == null) return null;	// nothing found

      if( !rsdb.getResultSet().next()) return null;	// empty resultset

      mag = parseResultSet(rsdb, 0);

      sm.close();
  }
  catch (SQLException ex) {
      System.err.println(ex);
      ex.printStackTrace();

  }

  return mag;

    }
   /**
     * Returns ALL the Magnitudes associate with the event with this ID number
     * from the data source. This will return a Collection of alternate Magnitude
     * objects and will NOT contain the preferred mag.
     * Returns null if no mags are found.<p>
     * Uses the default DataSource.
     */
    public Collection getAltBySolutionId (long id)
    {
  return getAltBySolutionId(DataSource.getConnection(), id);
    }
   /**
     * Returns ALL the Magnitudes associate with the event with this ID number
     * from the data source. This will return a Collection of alternate Magnitude
     * objects and will NOT contain the preferred mag.
     * Returns null if no mags are found.<p>
     * Uses the default DataSource.
     */
    public Collection getAltBySolutionId (Connection conn, long id) {

  ArrayList magList = new ArrayList();

  try{
      if (conn.isClosed())	// check that valid connection exists
    {
        System.err.println ("* Connection is closed.");
        return null;
    }

      // Must do join to find prefor and prefmag of the given evid
      String sql = "Select "+NetMag.QUALIFIED_COLUMN_NAMES+
    " from event, netmag " +
    " WHERE (event.evid = " + id +") and (netmag.orid = Event.prefor)";

      Statement sm = conn.createStatement();

      //	    System.out.println ("SQL: "+sql);

      ResultSetDb rsdb = new ResultSetDb(ExecuteSQL.rowQuery(sm, sql));

      if (rsdb == null) return null;	// nothing found

      //parse the resultset
      while ( rsdb.getResultSet().next() ) {
         magList.add(parseResultSet(rsdb, 0));
      }
      sm.close();
  }
  catch (SQLException ex) {
      System.err.println(ex);
      ex.printStackTrace();

  }

  return magList;
    }
/**
 * Return the magid .
 * If there is none, one will be assigned from the dbase sequence.
 */
    public long getMagidValue() {

       if (magid.isNull()) magid.setValue(SeqIds.getNextSeq("magseq"));

    return magid.longValue();
    }
/**
 * Return the magid DataObject.
 */
    public DataLong getMagid() {
    return magid;
    }

    /**
     * Associate this mag with this Solution.
     * Overrides Magnitude.associate() to include orid of mag to that of sol.
     */
    public void associate(Solution sol) {

  super.associate(sol);
     // get orid, if null will assign one
     long id = ((SolutionTN)sol).getOrid();
     setOrid(id);
    }

    /**
     * Returns true if all not-NULL fields are not-Null. Does not check other
     * constraints.  Does not check MAGID because that will be assigned from the
     * sequence if it is missing.  Does check nullness of: value, type,
     * authority and orid.  */
    protected boolean isSufficient() {

  if (value.isNull() ||
      subScript.isNull() ||
      authority.isNull() ||
      orid.isNull())	return false;

  return true;
    }

    /*
      STATES:
      o  The class has a boolean deleteFlag.
      o  The fromDbase boolean tells us if we will 'insert' or 'update' on commit.
      o  If the individual DataObject.isUpdate() = true,  an update is necessary.

      Commit action matrix:

      fromDbase		=	true		false
      deleteFlag=true           dbaseDelete	noop
      isUpdate()=true		update		insert
      isUpdate()=false		noop		insert

     */

    /** Write new NetMag row to the DataSource. Will not write a row and return 'false'
        if:<br>
        1) DataSource.isWriteBackEnabled() is false<br>
        2) The magnitude was from the dbase and has not changed<br>
        3) Any fields required by the dbase are not set in the Magnitude <br>
        4) Other errors occur <br>
        DataSource.setWriteBackEnabled(true) must be set BEFORE data is
        read. Don't forget to to set 'prefmag' in the Event table = magid.<p>

        Write amps or codas and associations.
        If this is the prefered mag set it so in the dbase.
        */
    public boolean commit() throws JasiCommitException {

  // can you write to the dbase?
  if (!DataSource.isWriteBackEnabled())
          throw new JasiCommitException("Database is NOT write enabled.");

  if (this.isNull() || isDeleted() || !hasChanged()) return false;

  // are all not-null values assigned?
        if (!isSufficient()) throw new JasiCommitException("Malformed magnitude.");

  // this will force a new magid to be gotten from the dbase seq
  magid.setMutable(true);         // allow changing a key field
  magid.setNull(true);

  // create the DataTableRow
  netMagRow = toNetMagRow();
        if (netMagRow.isNull()) throw new JasiCommitException("Malformed magnitude.");
  netMagRow.setProcessing(DataTableRowStates.INSERT);

  if (debug) System.out.println(netMagRow.toString()); 	// debug

  boolean status = (netMagRow.insertRow(DataSource.getConnection()) > 0);

        // success - do the rest
        if (status) {     // new NetMag was written

           setUpdate(false);    // now there's a dbase row

           // if this is the prefered mag
           if (this.isPreferred()) {
             ((SolutionTN)sol).dbaseSetPrefMag(this);
           }

           // commit all the contributing amplitudes
           commitAmpList();

          // commit coda list elements
          commitCodaList();

       } else {
          throw new JasiCommitException("Magnitude insert failed.");
       }

  return status;
    }
/**
 * Use the logic in the dbase to set the preferred magnitude from among all those
 * in the dbase associated with this event. Returns the magid of the preferred mag.
 * Returns 0 if no pref mag was set. <p>
 * Note that this call issues a database commit.
 */

    public static long dbaseAutoSetPrefMag(Connection conn, long evid) {

  String sql = "{? = call MagPref.setPrefMagOfEvent (?)}";

  try {

      CallableStatement cs = conn.prepareCall(sql);

      cs.registerOutParameter (1, java.sql.Types.BIGINT);
      cs.setDouble(2, evid);

      ResultSet rs = cs.executeQuery();

      long result  = cs.getLong(1);
      cs.close();

         // dbase returns neg. if no change, don't want to do that here.
         return Math.abs(result);

      } catch (SQLException ex) {
    System.out.println ("SQL=\n"+sql);
    System.err.println(ex);
    ex.printStackTrace();
    return -1;
      }
    }

/** Make dbase prepared statement to get mag priority. */
     protected static boolean prepMagPriority (Connection conn) {
        if (magPrioStatement == null) {

        if (conn == null) return false;

        try {
            magPrioStatement =
                  DataSource.getConnection().prepareStatement(
                  "Select MagPref.getMagPriority(?, ?, ?, ?, ?, ?, ?) from DUAL");
           } catch	 (SQLException ex) {
                System.err.println("prepMagPriority couldn't make prepared statement.");
                System.err.println(ex);
             ex.printStackTrace();
                return false;
           }
        }

        return true;

     }

/**
 * Use the logic in the dbase to calculate the priority of this magnitude.
 * Returns 0 if this mag is undefined.
 */
    public int getPriority() {
  // We can't do this at instatiation time because the Connection is not created yet.
  if (magPrioStatement == null) prepMagPriority (DataSource.getConnection());

// make the query
  try {
      // set the 7 args
      magPrioStatement.setString(1, this.subScript.toString());
      magPrioStatement.setString(2, this.authority.toString());
      magPrioStatement.setString(3, this.source.toString());
      magPrioStatement.setString(4, this.method.toString());
      magPrioStatement.setInt   (5, this.getReadingsUsed());  // stations?
      magPrioStatement.setFloat (6, this.value.floatValue());
      magPrioStatement.setFloat (7, this.quality.floatValue());

      ResultSet rset = magPrioStatement.executeQuery();

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -