예제 #1
0
  /** ensure that non-Manual components of flow_tuple have equal dataRanges symmetric about 0.0 */
  public static void equalizeFlow(Vector mapVector, DisplayTupleType flow_tuple)
      throws VisADException, RemoteException {
    double[] range = new double[2];
    double low = Double.MAX_VALUE;
    double hi = -Double.MAX_VALUE;
    boolean anyAuto = false;

    Enumeration maps = mapVector.elements();
    while (maps.hasMoreElements()) {
      ScalarMap map = ((ScalarMap) maps.nextElement());
      DisplayRealType dtype = map.getDisplayScalar();
      DisplayTupleType tuple = dtype.getTuple();
      if (flow_tuple.equals(tuple) && !map.isManual && !map.badRange()) {
        anyAuto = true;
        low = Math.min(low, map.dataRange[0]);
        hi = Math.max(hi, map.dataRange[1]);
      }
    }
    if (!anyAuto) return;
    hi = Math.max(hi, -low);
    low = -hi;
    maps = mapVector.elements();
    while (maps.hasMoreElements()) {
      ScalarMap map = ((ScalarMap) maps.nextElement());
      DisplayRealType dtype = map.getDisplayScalar();
      DisplayTupleType tuple = dtype.getTuple();
      if (flow_tuple.equals(tuple) && !map.isManual && !map.badRange()) {
        map.setRange(null, low, hi, false);
      }
    }
  }
예제 #2
0
 public String[] getUserList() throws RemoteException {
   Vector<String> res = new Vector<String>();
   for (ChatUser CU : userstable.values()) {
     res.add(CU.getName());
   }
   return res.toArray(new String[] {});
 }
예제 #3
0
  public static boolean are_d_connected(AbstractVariable x1, AbstractVariable x2, Vector evidence)
      throws RemoteException {
    // Find all paths between x1 and x2, then see if there is some path which is
    // d-connecting given the evidence. If so, return true, otherwise false.

    Hashtable path_sets = new Hashtable(); // HEY !!! THIS OUGHT TO BE CACHED SOMEWHERE !!!
    PathAnalysis.compile_paths(x1, x2, path_sets);

    Vector path_set = (Vector) path_sets.get(new VariablePair(x1, x2));
    if (path_set == null)
      // No connections whatsoever.
      return false;

    Enumeration path_set_enum = path_set.elements();
    while (path_set_enum.hasMoreElements()) {
      AbstractVariable[] path = (AbstractVariable[]) path_set_enum.nextElement();
      if (is_d_connecting(path, evidence)) {
        System.err.print("PathAnalysis.are_d_connected: path ");
        int i;
        for (i = 0; i < path.length; i++) System.err.print(path[i].get_name() + " ");
        System.err.print("is d-connected given evidence ");
        for (i = 0; i < evidence.size(); i++)
          System.err.print(((AbstractVariable) evidence.elementAt(i)).get_name() + " ");
        System.err.println("");
        return true;
      }
    }

    return false;
  }
예제 #4
0
  /**
   * When this class is loaded, preload the cache with a few items which we think will often be
   * needed. This can avoid the necessity of running a belief network context in simple problems.
   */
  static {
    System.err.println("PiHelperLoader.static: preload the helper cache.");

    helper_cache = new Hashtable();
    Vector seq = new Vector();

    seq.addElement(riso.distributions.ConditionalDiscrete.class);
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("pi", seq),
        riso.distributions.computes_pi.ConditionalDiscrete_Discrete.class);

    seq = new Vector();
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("lambda", seq), riso.distributions.computes_lambda.Discrete.class);

    seq = new Vector();
    seq.addElement(riso.distributions.AbstractDistribution.class);
    seq.addElement(riso.distributions.AbstractDistribution.class);

    helper_cache.put(
        new HelperCacheKey("pi_message", seq),
        riso.distributions.computes_pi_message.AbstractDistribution_AbstractDistribution.class);

    seq = new Vector();
    seq.addElement(riso.distributions.ConditionalDiscrete.class);
    seq.addElement(riso.distributions.Discrete.class);
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("lambda_message", seq),
        riso.distributions.computes_lambda_message.ConditionalDiscrete_Discrete_Discrete.class);

    seq = new Vector();
    seq.addElement(riso.distributions.ConditionalDiscrete.class);
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("lambda_message", seq),
        riso.distributions.computes_lambda_message.ConditionalDiscrete_Discrete_.class);

    seq = new Vector();
    seq.addElement(riso.distributions.Discrete.class);
    seq.addElement(riso.distributions.Discrete.class);

    helper_cache.put(
        new HelperCacheKey("posterior", seq),
        riso.distributions.computes_posterior.Discrete_Discrete.class);

    System.err.println("PiHelperLoader.static: helper_cache.size(): " + helper_cache.size());
  }
예제 #5
0
 private int logContains(int xId) {
   synchronized (logArray) {
     for (int i = 0; i < logArray.size(); i++) {
       Log temp = (Log) logArray.elementAt(i);
       if (temp.getXId() == xId) {
         return i;
       }
     }
   }
   return -1;
 }
예제 #6
0
  /* reserve an itinerary */
  public boolean itinerary(
      int id, int customer, Vector flightNumbers, String location, boolean Car, boolean Room)
      throws RemoteException {
    int noFlight = flightNumbers.size();
    boolean result = false;
    ;
    for (int i = 0; i < noFlight; i++) {
      result = reserveFlight(id, customer, Integer.parseInt(flightNumbers.get(i).toString()));
      if (!result) break;
    }

    return result;
  }
예제 #7
0
 /** Send a <CODE>ScalarMapEvent</CODE> to all control listeners */
 private void notifyCtlListeners(ScalarMapControlEvent evt)
     throws RemoteException, VisADException {
   if (ListenerVector != null) {
     Vector listeners_clone = null;
     synchronized (ListenerVector) {
       listeners_clone = (Vector) ListenerVector.clone();
     }
     Enumeration listeners = listeners_clone.elements();
     while (listeners.hasMoreElements()) {
       ScalarMapListener listener = (ScalarMapListener) listeners.nextElement();
       listener.controlChanged(evt);
     }
   }
 }
예제 #8
0
 private void writeDataToLog(int xId, String key, RMItem value) {
   System.out.println("entering writedatatolog");
   synchronized (logArray) {
     Log temp;
     int indx;
     if ((indx = logContains(xId)) != -1) {
       temp = (Log) logArray.elementAt(indx);
       temp.put(key, value);
     } else {
       temp = new Log(xId, new RMHashtable());
       temp.put(key, value);
       logArray.add(temp);
     }
   }
 }
예제 #9
0
  /**
   * A <tt>path</tt> between <tt>x1</tt> and <tt>x2</tt> is d-connecting given <tt>evidence</tt> if
   * every interior node <tt>n</tt> in the path has the property that either
   *
   * <ol>
   *   <li><tt>n</tt> is linear or diverging and <tt>n</tt> is not in <tt>evidence</tt>, or
   *   <li><tt>n</tt> is converging, and either <tt>n</tt> or some descendent of <tt>n</tt> is in
   *       <tt>evidence</tt>.
   * </ol>
   */
  public static boolean is_d_connecting(AbstractVariable[] path, Vector evidence)
      throws RemoteException {
    for (int i = 1; i < path.length - 1; i++) {
      if (is_converging(path[i - 1], path[i], path[i + 1])) {
        // System.err.println( "PathAnalysis.is_d_connecting: "+path[i].get_name()+" is converging."
        // );
        if (!evidence.contains(path[i]) && !contains_descendent(evidence, path[i])) return false;
      } else {
        // System.err.println( "PathAnalysis.is_d_connecting: "+path[i].get_name()+" is linear or
        // diverging." );
        if (evidence.contains(path[i])) return false;
      }
    }

    return true;
  }
예제 #10
0
  public static PiHelper load_pi_helper(
      PiHelper pi_helper_cache, ConditionalDistribution pxu, Distribution[] pi_messages)
      throws Exception {
    if (pi_messages.length == 0) return new TrivialPiHelper();

    Vector seq = new Vector();
    seq.addElement(pxu.getClass());
    for (int i = 0; i < pi_messages.length; i++) seq.addElement(pi_messages[i].getClass());

    if (pi_helper_cache != null
        && MatchClassPattern.matches(pi_helper_cache.description(), seq, new int[1], new int[1]))
      return pi_helper_cache;

    Class c = find_helper_class(seq, "pi");
    return (PiHelper) c.newInstance();
  }
예제 #11
0
  /** Retrieve next page size of objects from the remote cursored stream */
  public Vector cursoredStreamNextPage(
      RemoteCursoredStream remoteCursoredStream,
      ReadQuery query,
      DistributedSession session,
      int pageSize) {
    Transporter transporter = null;
    try {
      transporter =
          getRemoteSessionController()
              .cursoredStreamNextPage(new Transporter(remoteCursoredStream.getID()), pageSize);
    } catch (RemoteException exception) {
      throw CommunicationException.errorInInvocation(exception);
    }

    if (transporter == null) {
      return null;
    }

    if (!transporter.wasOperationSuccessful()) {
      throw transporter.getException();
    }

    Vector serverNextPageObjects = (Vector) transporter.getObject();
    if (serverNextPageObjects == null) {
      cursoredStreamClose(remoteCursoredStream.getID());
      return null;
    }
    Vector clientNextPageObjects = serverNextPageObjects;
    if (query.isReadAllQuery() && (!query.isReportQuery())) { // could be DataReadQuery
      clientNextPageObjects = new Vector(serverNextPageObjects.size());
      for (Enumeration objEnum = serverNextPageObjects.elements(); objEnum.hasMoreElements(); ) {
        // 2612538 - the default size of Map (32) is appropriate
        Object clientObject =
            session.getObjectCorrespondingTo(
                objEnum.nextElement(),
                transporter.getObjectDescriptors(),
                new IdentityHashMap(),
                (ObjectLevelReadQuery) query);
        clientNextPageObjects.addElement(clientObject);
      }
    }

    return clientNextPageObjects;
  }
  /**
   * This Method returns the 2D Array which is the list of the Items for the selected WorkOrder of
   * the Customer.
   *
   * @param workorderId - WorkOrder Id Foreign Key of WRK_ORDR_DETS table
   * @return Object[][] - 2D Array which is List of the Items for the WorkOrder
   */
  public Object[][] getWorkOrderItems(long workorderId) throws RemoteException {

    WrkOrdrDets wrkordrdts_obj = new WrkOrdrDets(conn);

    RHCCBlgKeys blgkeys_obj = new RHCCBlgKeys(conn);

    Vector workorderdetList = wrkordrdts_obj.getProductList(workorderId);

    // Hashtable BSysList = (Hashtable) USFEnv.getBillSystems();
    BlgSys blgsys = new BlgSys();

    Hashtable BSysList = (Hashtable) blgsys.searchBlgSys();

    Enumeration BSys = BSysList.keys();

    // The 2-Dimensional array to hold the Items Billing System wise.
    Object[][] prodList = new Object[BSysList.size()][workorderdetList.size() + 1];

    // The Number of Billing Systems are assumed to be equal to the
    // Static Load Billing Systems Hashtable size. The Billing Systems will
    // be in order starting from 1 and incrementing by one.
    for (int i = 0; i < BSysList.size(); i++) {
      // Set the 2D array to store the Billing System as the first element
      // of each row.
      prodList[i][0] = String.valueOf(i + 1);
    }

    // Loop throught the WorkOrder Items List and place them in the appropriate
    // positions in the 2D array.
    for (int j = 0; j < workorderdetList.size(); j++) {
      // Determine the Billing System of the Product
      Vector tmpVector = new Vector();

      WrkOrdrDets workorderObj = (WrkOrdrDets) workorderdetList.elementAt(j);

      RHCCBlgKeys bkObj =
          blgkeys_obj.searchRHCCBlgKeys(((WrkOrdrDets) workorderdetList.elementAt(j)).getRBKID());
      int bsid = (new Long(bkObj.getBsId())).intValue();

      tmpVector.addElement(bkObj);
      tmpVector.addElement(workorderObj);

      // Based on the Billing System Id retreived place the Product Object
      // in the 2D array.
      int k = 1;
      while (prodList[bsid - 1][k] != null) {
        k = k + 1;
      }
      prodList[bsid - 1][k] = tmpVector;
    }

    // Return the 2D array
    return prodList;
  }
예제 #13
0
 private RMItem readDataFromLog(int id, String key, int xId) {
   synchronized (logArray) {
     int indx;
     if ((indx = logContains(xId)) != -1) {
       Log temp = (Log) logArray.elementAt(indx);
       return (RMItem) temp.get(key);
     }
   }
   return null;
 }
예제 #14
0
 public void sendMessage(ChatMessage m) throws RemoteException {
   Vector<String> fallidos = new Vector<String>();
   for (String uname : userstable.keySet()) {
     try {
       userstable.get(uname).sendMessage(m);
     } catch (Exception E) {
       fallidos.add(uname);
       System.out.println("no se lo he podido enviar a " + uname);
     }
   }
   for (String uname : fallidos) {
     try {
       leaveUser(userstable.get(uname));
     } catch (Exception E) {
       System.out.println("realmente " + uname + " se ha ido , lo borro");
       userstable.remove(uname);
       broadcastLeaving(uname);
     }
   }
 }
예제 #15
0
  public static void find_all_paths(
      AbstractVariable x, AbstractVariable end, Vector path_set, Stack path_stack)
      throws RemoteException {
    int i;

    path_stack.push(x);

    if (x == end) {
      // Construct a path from the beginning to the end, using what's on the stack.

      AbstractVariable[] path = new AbstractVariable[path_stack.size()];

      // System.err.println( "\tFound path: " );
      Enumeration e;
      for (i = 0, e = path_stack.elements(); e.hasMoreElements(); i++) {
        path[i] = (AbstractVariable) e.nextElement();
        // System.err.print( path[i].get_name()+" " );
      }
      // System.err.println("");

      path_set.addElement(path);
      path_stack.pop();
      return;
    }

    AbstractVariable[] parents = x.get_parents();
    for (i = 0; i < parents.length; i++) {
      Enumeration e = path_stack.elements();
      boolean is_on_stack = false;
      while (e.hasMoreElements())
        if (e.nextElement() == parents[i]) {
          is_on_stack = true;
          break;
        }

      if (!is_on_stack) find_all_paths(parents[i], end, path_set, path_stack);
    }

    AbstractVariable[] children = x.get_children();
    for (i = 0; i < children.length; i++) {
      Enumeration e = path_stack.elements();
      boolean is_on_stack = false;
      while (e.hasMoreElements())
        if (e.nextElement() == children[i]) {
          is_on_stack = true;
          break;
        }

      if (!is_on_stack) find_all_paths(children[i], end, path_set, path_stack);
    }

    path_stack.pop();
  }
예제 #16
0
  public static boolean contains_descendent(Vector evidence, AbstractVariable a)
      throws RemoteException {
    AbstractVariable[] children = a.get_children();
    if (children == null) return false;

    for (int i = 0; i < children.length; i++) {
      if (evidence.contains(children[i])) return true;
      else if (contains_descendent(evidence, children[i])) return true;
    }

    return false;
  }
예제 #17
0
  public String toString() {
    String s = "[" + helper_type + ";";
    for (Enumeration e = seq.elements(); e.hasMoreElements(); ) {
      try {
        Class c = (Class) e.nextElement();
        s += c.getName() + ",";
      } catch (NoSuchElementException ee) {
        s += "???" + ",";
      }
    }

    return s + "]";
  }
예제 #18
0
 /**
  * add a ScalarMapListener, to be notified whenever setRange is invoked
  *
  * @param listener <CODE>ScalarMapListener</CODE> to recieve notification of changes.
  */
 public void addScalarMapListener(ScalarMapListener listener) {
   if (ListenerVector == null) {
     ListenerVector = new Vector();
   }
   ListenerVector.addElement(listener);
   if (dataRange[0] == dataRange[0] && dataRange[1] == dataRange[1]) {
     try {
       listener.mapChanged(new ScalarMapEvent(this, ScalarMapEvent.MANUAL));
     } catch (VisADException e) {
     } catch (RemoteException e) {
     }
   }
 }
예제 #19
0
  public void abort(int transactionId) throws RemoteException, InvalidTransactionException {
    int indx = logContains(transactionId);

    Log temp;

    if (indx > -1) {

      temp = (Log) logArray.elementAt(indx);

    } else {
      System.out.println("nothing in array");
      return;
    }

    for (Enumeration e = temp.getKeys(); e.hasMoreElements(); ) {
      System.out.println("For loop");
      String key = (String) (e.nextElement());
      RMItem obj = temp.get(key);
      if (obj.getType() == 0) {
        Flight flight = (Flight) obj;
        if (flight.getCount() == -1) {
          System.out.println("entering count=-1 block");
          removeData(transactionId, key);
        } else {
          System.out.println("entering other block");
          writeData(transactionId, key, flight);
        }
      } else if (obj.getType() == 1) {
        Customer cust = (Customer) obj;
        if (cust.getID() == -1) {
          System.out.println("entering remove data for customer");
          removeData(transactionId, key);
        } else {
          System.out.println("entering write data for customer");
          writeData(transactionId, key, obj);
        }
      }
    }
  }
예제 #20
0
  /** set range used for linear map from Scalar to DisplayScalar values */
  private synchronized void setRange(
      DataShadow shadow, double low, double hi, boolean unit_flag, int remoteId)
      throws VisADException, RemoteException {
    int i = ScalarIndex;
    if (shadow != null) {
      // WLH - 23 Sept 99
      if (DisplayScalar.equals(Display.Latitude) || DisplayScalar.equals(Display.Longitude)) {
        Unit data_unit = (Scalar instanceof RealType) ? ((RealType) Scalar).getDefaultUnit() : null;
        Unit display_unit = DisplayScalar.getDefaultUnit();
        if (data_unit != null && display_unit != null && Unit.canConvert(data_unit, display_unit)) {
          dataRange[0] = data_unit.toThis(displayRange[0], display_unit);
          dataRange[1] = data_unit.toThis(displayRange[1], display_unit);
        } else {
          if (i < 0 || i >= shadow.ranges[0].length) return;
          dataRange[0] = shadow.ranges[0][i];
          dataRange[1] = shadow.ranges[1][i];
        }
      } else {
        if (i < 0 || i >= shadow.ranges[0].length) return;
        dataRange[0] = shadow.ranges[0][i];
        dataRange[1] = shadow.ranges[1][i];
      }
    } else if (unit_flag) {
      Unit data_unit = (Scalar instanceof RealType) ? ((RealType) Scalar).getDefaultUnit() : null;
      Unit display_unit = DisplayScalar.getDefaultUnit();
      if (data_unit == null || display_unit == null) {
        throw new UnitException("ScalarMap.setRangeByUnits: null Unit");
      }
      dataRange[0] = data_unit.toThis(displayRange[0], display_unit);
      dataRange[1] = data_unit.toThis(displayRange[1], display_unit);
      /*
      System.out.println("data_unit = " + data_unit + " display_unit = " + display_unit);
      System.out.println("dataRange = " + dataRange[0] + " " + dataRange[1] +
      " displayRange = " + displayRange[0] + " " + displayRange[1]);
      */
    } else {
      dataRange[0] = low;
      dataRange[1] = hi;
      // WLH 31 Aug 2000
      // manual range is in overrideUnit. so convert to Scalar default Unit
      if (overrideUnit != null) {
        dataRange[0] = (dataRange[0] - override_offset) / override_scale;
        dataRange[1] = (dataRange[1] - override_offset) / override_scale;
      }
    }
    /*
    if (shadow != null || remoteId != VisADEvent.LOCAL_SOURCE) {
      System.out.println(Scalar + " -> " + DisplayScalar + " range: " + dataRange[0] +
                         " to " + dataRange[1] + " " + display.getName());
    }
    */
    // at this point dataRange is range for Scalar default Unit
    //   even if (overrideUnit != null)
    // DRM 17 Feb 2006 - so set the defaultUnitRange to be these values.
    defaultUnitRange[0] = dataRange[0];
    defaultUnitRange[1] = dataRange[1];
    if (defaultUnitRange[0] == defaultUnitRange[1]) {
      double half = defaultUnitRange[0] / 2000.0;
      if (half < 0.5) half = 0.5;
      defaultUnitRange[0] -= half;
      defaultUnitRange[1] += half;
    }

    if (isScaled) {
      computeScaleAndOffset();
    } else { // if (!isScaled)
      if (dataRange[0] == Double.MAX_VALUE || dataRange[1] == -Double.MAX_VALUE) {
        dataRange[0] = Double.NaN;
        dataRange[1] = Double.NaN;
      }

      // WLH 31 Aug 2000
      if (overrideUnit != null) {
        // now convert dataRange to overrideUnit
        dataRange[0] = defaultUnitRange[0] * override_scale + override_offset;
        dataRange[1] = defaultUnitRange[1] * override_scale + override_offset;
      }
    }
    /*
    System.out.println(Scalar + " -> " + DisplayScalar + " range: " + dataRange[0] +
                       " to " + dataRange[1] + " scale: " + scale + " " + offset);
    */
    if (DisplayScalar.equals(Display.Animation) && shadow != null) {
      if (control != null && ((AnimationControl) control).getComputeSet()) {
        Set set = shadow.animationSampling;
        /* DRM: 04 Jan 2003
        if (set == null) {
          return;
        }
        */
        ((AnimationControl) control).setSet(set, true);
      }
    } else if (DisplayScalar.equals(Display.IsoContour)) {
      if (control != null) {

        // WLH 10 July 2002
        // don't set if application has called control.setLevels()
        float[] lowhibase = new float[3];
        boolean[] dashes = new boolean[1];

        boolean public_set = ((ContourControl) control).getPublicSet();
        if (!public_set) {
          boolean[] bvalues = new boolean[2];
          float[] values = new float[5];
          ((ContourControl) control).getMainContours(bvalues, values);
          if (shadow == null) {
            // don't set surface value for auto-scale
            values[0] = (float) dataRange[0]; // surfaceValue
          }
          // CTR: 29 Jul 1999: interval should never be zero
          float f = (float) (dataRange[1] - dataRange[0]) / 10.0f;
          if (f != 0.0f) values[1] = f; // contourInterval
          values[2] = (float) dataRange[0]; // lowLimit
          values[3] = (float) dataRange[1]; // hiLimit
          values[4] = (float) dataRange[0]; // base
          ((ContourControl) control).setMainContours(bvalues, values, true, true);
        }
      }
    } else if (DisplayScalar.equals(Display.XAxis)
        || DisplayScalar.equals(Display.YAxis)
        || DisplayScalar.equals(Display.ZAxis)) {
      if (dataRange[0] != Double.MAX_VALUE
          && dataRange[1] != -Double.MAX_VALUE
          && dataRange[0] == dataRange[0]
          && dataRange[1] == dataRange[1]
          && dataRange[0] != dataRange[1]
          && scale == scale
          && offset == offset) {
        if (display != null) {
          makeScale();
        } else {
          scale_flag = true;
        }
        back_scale_flag = true;
      }
    }

    if (dataRange[0] == dataRange[0] && dataRange[1] == dataRange[1] && ListenerVector != null) {
      ScalarMapEvent evt;
      evt =
          new ScalarMapEvent(
              this, (shadow == null ? ScalarMapEvent.MANUAL : ScalarMapEvent.AUTO_SCALE), remoteId);
      Vector listeners_clone = null;
      synchronized (ListenerVector) {
        listeners_clone = (Vector) ListenerVector.clone();
      }
      Enumeration listeners = listeners_clone.elements();
      while (listeners.hasMoreElements()) {
        ScalarMapListener listener = (ScalarMapListener) listeners.nextElement();
        listener.mapChanged(evt);
      }
    }
  }
예제 #21
0
  public synchronized void drag_direct(VisADRay ray, boolean first, int mouseModifiers) {
    if (barbValues == null || ref == null || shadow == null) return;

    if (first) {
      stop = false;
    } else {
      if (stop) return;
    }

    // modify direction if mshift != 0
    // modify speed if mctrl != 0
    // modify speed and direction if neither
    int mshift = mouseModifiers & InputEvent.SHIFT_MASK;
    int mctrl = mouseModifiers & InputEvent.CTRL_MASK;

    float o_x = (float) ray.position[0];
    float o_y = (float) ray.position[1];
    float o_z = (float) ray.position[2];
    float d_x = (float) ray.vector[0];
    float d_y = (float) ray.vector[1];
    float d_z = (float) ray.vector[2];

    if (pickCrawlToCursor) {
      if (first) {
        offset_count = OFFSET_COUNT_INIT;
      } else {
        if (offset_count > 0) offset_count--;
      }
      if (offset_count > 0) {
        float mult = ((float) offset_count) / ((float) OFFSET_COUNT_INIT);
        o_x += mult * offsetx;
        o_y += mult * offsety;
        o_z += mult * offsetz;
      }
    }

    if (first || refirst) {
      point_x = barbValues[2];
      point_y = barbValues[3];
      point_z = 0.0f;
      line_x = 0.0f;
      line_y = 0.0f;
      line_z = 1.0f; // lineAxis == 2 in DataRenderer.drag_direct
    } // end if (first || refirst)

    float[] x = new float[3]; // x marks the spot
    // DirectManifoldDimension = 2
    // intersect ray with plane
    float dot = (point_x - o_x) * line_x + (point_y - o_y) * line_y + (point_z - o_z) * line_z;
    float dot2 = d_x * line_x + d_y * line_y + d_z * line_z;
    if (dot2 == 0.0) return;
    dot = dot / dot2;
    // x is intersection
    x[0] = o_x + dot * d_x;
    x[1] = o_y + dot * d_y;
    x[2] = o_z + dot * d_z;
    /*
    System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
    */
    try {

      Tuple data = (Tuple) link.getData();
      int n = ((TupleType) data.getType()).getNumberOfRealComponents();
      Real[] reals = new Real[n];

      int k = 0;
      int m = data.getDimension();
      for (int i = 0; i < m; i++) {
        Data component = data.getComponent(i);
        if (component instanceof Real) {
          reals[k++] = (Real) component;
        } else if (component instanceof RealTuple) {
          for (int j = 0; j < ((RealTuple) component).getDimension(); j++) {
            reals[k++] = (Real) ((RealTuple) component).getComponent(j);
          }
        }
      }

      if (first || refirst) {
        // get first Data flow vector
        for (int i = 0; i < 3; i++) {
          int j = flowToComponent[i];
          data_flow[i] = (j >= 0) ? (float) reals[j].getValue() : 0.0f;
        }

        if (coord != null) {
          float[][] ds = {{data_flow[0]}, {data_flow[1]}, {data_flow[2]}};
          ds = coord.toReference(ds);
          data_flow[0] = ds[0][0];
          data_flow[1] = ds[1][0];
          data_flow[2] = ds[2][0];
        }

        data_speed =
            (float)
                Math.sqrt(
                    data_flow[0] * data_flow[0]
                        + data_flow[1] * data_flow[1]
                        + data_flow[2] * data_flow[2]);
        float barb0 = barbValues[2] - barbValues[0];
        float barb1 = barbValues[3] - barbValues[1];
        /*
        System.out.println("data_flow = " + data_flow[0] + " " + data_flow[1] +
                           " " + data_flow[2]);
        System.out.println("barbValues = " + barbValues[0] + " " + barbValues[1] +
                           "   " + barbValues[2] + " " + barbValues[3]);
        System.out.println("data_speed = " + data_speed);
        */
      } // end if (first || refirst)

      // convert x to a flow vector, and from spatial to earth
      if (getRealVectorTypes(which_barb) instanceof EarthVectorType) {
        // don't worry about vector magnitude -
        // data_speed & display_speed take care of that
        float eps = 0.0001f; // estimate derivative with a little vector
        float[][] spatial_locs = {
          {barbValues[0], barbValues[0] + eps * (x[0] - barbValues[0])},
          {barbValues[1], barbValues[1] + eps * (x[1] - barbValues[1])},
          {0.0f, 0.0f}
        };
        /*
        System.out.println("spatial_locs = " + spatial_locs[0][0] + " " +
                           spatial_locs[0][1] + " " + spatial_locs[1][0] + " " +
                           spatial_locs[1][1]);
        */
        float[][] earth_locs = spatialToEarth(spatial_locs);
        // WLH - 18 Aug 99
        if (earth_locs == null) return;
        /*
        System.out.println("earth_locs = " + earth_locs[0][0] + " " +
                           earth_locs[0][1] + " " + earth_locs[1][0] + " " +
                           earth_locs[1][1]);
        */
        x[2] = 0.0f;
        x[0] =
            (earth_locs[1][1] - earth_locs[1][0])
                * ((float) Math.cos(Data.DEGREES_TO_RADIANS * earth_locs[0][0]));
        x[1] = earth_locs[0][1] - earth_locs[0][0];
        /*
        System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
        */
      } else { // if (!(getRealVectorTypes(which_barb) instanceof EarthVectorType))
        // convert x to vector
        x[0] -= barbValues[0];
        x[1] -= barbValues[1];

        // adjust for spatial map scalings but don't worry about vector
        // magnitude - data_speed & display_speed take care of that
        // also, spatial is Cartesian
        double[] ranges = getRanges();
        for (int i = 0; i < 3; i++) {
          x[i] /= ranges[i];
        }
        /*
        System.out.println("ranges = " + ranges[0] + " " + ranges[1] +
                           " " + ranges[2]);
        System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
        */
      }

      // WLH 6 August 99
      x[0] = -x[0];
      x[1] = -x[1];
      x[2] = -x[2];

      /* may need to do this for performance
            float[] xx = {x[0], x[1], x[2]};
            addPoint(xx);
      */

      float x_speed = (float) Math.sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]);
      /* WLH 16 April 2002 - from Ken
            if (x_speed < 0.000001f) x_speed = 0.000001f;
      */
      if (x_speed < 0.01f) x_speed = 0.01f;
      if (first || refirst) {
        display_speed = x_speed;
      }
      refirst = false;

      if (mshift != 0) {
        // only modify data_flow direction
        float ratio = data_speed / x_speed;
        x[0] *= ratio;
        x[1] *= ratio;
        x[2] *= ratio;
        /*
        System.out.println("direction, ratio = " + ratio + " " +
                           data_speed + " " + x_speed);
        System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
        */
      } else if (mctrl != 0) {
        // only modify data_flow speed
        float ratio = x_speed / display_speed;
        if (data_speed < EPS) {
          data_flow[0] = 2.0f * EPS;
          refirst = true;
        }
        x[0] = ratio * data_flow[0];
        x[1] = ratio * data_flow[1];
        x[2] = ratio * data_flow[2];
        /*
        System.out.println("speed, ratio = " + ratio + " " +
                           x_speed + " " + display_speed);
        System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
        */
      } else {
        // modify data_flow speed and direction
        float ratio = data_speed / display_speed;
        /*
        System.out.println("data_speed = " + data_speed +
                           " display_speed = " + display_speed +
                           " ratio = " + ratio + " EPS = " + EPS);
        System.out.println("x = " + x[0] + " " + x[1] +" " + x[2] +
                           " x_speed = " + x_speed);
          data_speed = 21.213203 display_speed = 0.01 ratio = 2121.3203 EPS = 0.2
          x = 1.6170928E-4 1.6021729E-4 -0.0 x_speed = 0.01
          wind = (0.3430372, 0.33987218) at (-35.0, 5.0)
        */
        if (data_speed < EPS) {
          data_flow[0] = 2.0f * EPS;
          x[0] = data_flow[0];
          x[1] = data_flow[1];
          x[2] = data_flow[2];
          refirst = true;
        } else {
          x[0] *= ratio;
          x[1] *= ratio;
          x[2] *= ratio;
        }
      }

      if (coord != null) {
        float[][] xs = {{x[0]}, {x[1]}, {x[2]}};
        xs = coord.fromReference(xs);
        x[0] = xs[0][0];
        x[1] = xs[1][0];
        x[2] = xs[2][0];
      }

      // now replace flow values
      Vector vect = new Vector();
      for (int i = 0; i < 3; i++) {
        int j = flowToComponent[i];
        if (j >= 0) {
          RealType rtype = (RealType) reals[j].getType();
          reals[j] = new Real(rtype, (double) x[i], rtype.getDefaultUnit(), null);

          // WLH 31 Aug 2000
          Real r = reals[j];
          Unit overrideUnit = null;
          if (directMap[i] != null) {
            overrideUnit = directMap[i].getOverrideUnit();
          }
          Unit rtunit = rtype.getDefaultUnit();
          // units not part of Time string
          if (overrideUnit != null
              && !overrideUnit.equals(rtunit)
              && !RealType.Time.equals(rtype)) {
            double d = (float) overrideUnit.toThis((double) x[0], rtunit);
            r = new Real(rtype, d, overrideUnit);
            String valueString = r.toValueString();
            vect.addElement(rtype.getName() + " = " + valueString);
          } else {
            // create location string
            vect.addElement(rtype.getName() + " = " + x[i]);
          }
        }
      }
      getDisplayRenderer().setCursorStringVector(vect);

      Data newData = null;
      // now build new RealTuple or Flat Tuple
      if (data instanceof RealTuple) {
        newData =
            new RealTuple(
                ((RealTupleType) data.getType()), reals, ((RealTuple) data).getCoordinateSystem());
      } else {
        Data[] new_components = new Data[m];
        k = 0;
        for (int i = 0; i < m; i++) {
          Data component = data.getComponent(i);
          if (component instanceof Real) {
            new_components[i] = reals[k++];
          } else if (component instanceof RealTuple) {
            Real[] sub_reals = new Real[((RealTuple) component).getDimension()];
            for (int j = 0; j < ((RealTuple) component).getDimension(); j++) {
              sub_reals[j] = reals[k++];
            }
            new_components[i] =
                new RealTuple(
                    ((RealTupleType) component.getType()),
                    sub_reals,
                    ((RealTuple) component).getCoordinateSystem());
          }
        }
        newData = new Tuple(new_components, false);
      }
      ref.setData(newData);
    } catch (VisADException e) {
      // do nothing
      System.out.println("drag_direct " + e);
      e.printStackTrace();
    } catch (RemoteException e) {
      // do nothing
      System.out.println("drag_direct " + e);
      e.printStackTrace();
    }
  }
예제 #22
0
  /**
   * transform data into a (Java3D or Java2D) scene graph; add generated scene graph components as
   * children of group; group is Group (Java3D) or VisADGroup (Java2D); value_array are inherited
   * valueArray values; default_values are defaults for each display.DisplayRealTypeVector; return
   * true if need post-process
   */
  public boolean doTransform(
      Object group,
      Data data,
      float[] value_array,
      float[] default_values,
      DataRenderer renderer,
      ShadowType shadow_api)
      throws VisADException, RemoteException {

    if (data.isMissing()) return false;
    if (LevelOfDifficulty == NOTHING_MAPPED) return false;

    if (!(data instanceof Text)) {
      throw new DisplayException("data must be Text: " + "ShadowTextType.doTransform");
    }

    // get some precomputed values useful for transform
    // length of ValueArray
    int valueArrayLength = display.getValueArrayLength();
    // mapping from ValueArray to DisplayScalar
    int[] valueToScalar = display.getValueToScalar();
    // mapping from ValueArray to MapVector
    int[] valueToMap = display.getValueToMap();
    Vector MapVector = display.getMapVector();

    // array to hold values for various mappings
    float[][] display_values = new float[valueArrayLength][];

    // ????
    // get values inherited from parent;
    // assume these do not include SelectRange, SelectValue
    // or Animation values - see temporary hack in
    // DataRenderer.isTransformControl
    int[] inherited_values = getInheritedValues();
    for (int i = 0; i < valueArrayLength; i++) {
      if (inherited_values[i] > 0) {
        display_values[i] = new float[1];
        display_values[i][0] = value_array[i];
      }
    }

    boolean[][] range_select =
        shadow_api.assembleSelect(
            display_values, 1, valueArrayLength, valueToScalar, display, shadow_api);

    if (range_select[0] != null && !range_select[0][0]) {
      // data not selected
      return false;
    }

    // get any text String and TextControl inherited from parent
    String text_value = shadow_api.getParentText();
    TextControl text_control = shadow_api.getParentTextControl();
    boolean anyText = getAnyText();
    if (anyText && text_value == null) {
      // get any text String and TextControl from this
      Vector maps = getSelectedMapVector();
      if (!maps.isEmpty()) {
        text_value = ((Text) data).getValue();
        ScalarMap map = (ScalarMap) maps.firstElement();
        text_control = (TextControl) map.getControl();
      }
    }

    //
    // never renders text ????
    //

    // add values to value_array according to SelectedMapVector
    if (getIsTerminal()) {
      // ????
      return terminalTupleOrScalar(
          group,
          display_values,
          text_value,
          text_control,
          valueArrayLength,
          valueToScalar,
          default_values,
          inherited_values,
          renderer,
          shadow_api);
    } else {
      // nothing to render at a non-terminal TextType
    }
    return false;
  }
예제 #23
0
  /**
   * This is the main controller logic for item selection servlet. This determines whether to show a
   * list of items for a WorkOrder, add a item, edit a item's detail information, or delete a item.
   * The product_action parameter is past to this servlet to determine what action to perform. The
   * product_action parameter is a button defined by JSPs related to product presentation screens.
   *
   * <p>The default action is to show all product related to a parent WorkOrder.
   *
   * @param req HttpServlet request
   * @param resp HttpServlet response
   */
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    WorkOrderDetailRemote workorderdetEJBean = null;

    securityChecks(req, resp);

    // Get the current session
    HttpSession session = req.getSession(false);
    if (session == null) return;

    String sTmp = "";

    // Get a new business logic EJB (custInfoEJBean)
    USFEnv.getLog().writeDebug("getting buslogic EJB", this, null);
    try {
      workorderdetEJBean = workorderdetHome.create();
      USFEnv.getLog().writeDebug("EJBean Created", this, null);
    } catch (CreateException e) {
      String errorMsg = "Critical Exception in ItemsServlet";
      USFEnv.getLog().writeCrit(errorMsg + " failed EJB creation", this, e);
      errorJSP(req, resp, errorMsg);
      return;
    } catch (RemoteException e) {
      String errorMsg = "Critical Exception in ItemsServlet";
      USFEnv.getLog().writeCrit(errorMsg + " failed EJB connect", this, e);
      errorJSP(req, resp, errorMsg);
      return;
    } catch (Exception e) {
      String errorMsg = "Critical Exception no EJB created";
      USFEnv.getLog().writeCrit(errorMsg + " failed EJB creation", this, e);
      errorJSP(req, resp, errorMsg);
      return;
    }

    try {

      // Button user pressed in the itemselection.jsp
      String sJSPAction = req.getParameter("product_action");
      USFEnv.getLog().writeWarn("product_action from JSP: " + sJSPAction, this, null);

      short year = Short.valueOf((String) session.getValue("Iyear")).shortValue();
      long customerId = Long.valueOf((String) session.getValue("rcustId")).longValue();
      long applicationId = Long.valueOf((String) session.getValue("rappid")).longValue();
      long workorderId = 0;
      long bkId = 0;
      long billkeyId = 0;
      long bsId = 0;
      long wodId = 0;
      String editflag = "";
      String bsNm = "";

      java.sql.Date strtDate = null;
      java.sql.Date endDate = null;
      String prodError = "";

      // Check to make sure session does have an WorkOrder ID
      if (session.getValue("WorkOrderId") != null) {
        // If Yes get the parent WorkOrder ID from session
        workorderId = Long.valueOf((String) session.getValue("WorkOrderId")).longValue();
      }

      // Button Action from JSP is empty then show the Default page of the
      // Product Listing.
      if (USFUtil.isBlank(sJSPAction)) {
        USFEnv.getLog().writeDebug("Display product list for FRN.", this, null);
        // list items for parent Work Order Number

        Vector billingsystems = null;

        WrkOrdrDets workorderdets = new WrkOrdrDets();

        billingsystems = workorderdets.getBillingSystems();

        req.setAttribute("BillingSystems", billingsystems);

        for (int s = 0; s < billingsystems.size(); s++)
          USFEnv.getLog()
              .writeDebug("INSIDE BILLING SYSTEMS " + billingsystems.elementAt(s), this, null);

        listProducts(workorderId, workorderdetEJBean, session, req, resp);
        return;
      }

      // Button action from JSP is to Add a new Item
      else if (sJSPAction.equals("add")) {
        // Remove the Product Object from session
        session.removeValue("prodObj");

        editflag = "addnew";
        req.setAttribute("editflag", editflag);

        // Read the Item and the Billing System for adding the New
        // Item.
        String formProdBsId = (String) req.getParameter("formProdId");
        String formProdId = formProdBsId.substring(0, formProdBsId.indexOf("|"));
        String formProdName = formProdBsId.substring(formProdBsId.indexOf("|") + 1);
        long rscId = (new Long(formProdId).longValue());
        // bsId = (new Long( formBsId ).longValue()) ;
        String billSystem = formProdName.substring(0, formProdName.indexOf("-"));
        String itemName = formProdName.substring(formProdName.indexOf("-") + 1);

        BlgSys blgSys = new BlgSys();
        bsId = blgSys.getBsId(billSystem);

        // Create db connection for EJB
        workorderdetEJBean.connect();

        // Get the WorkOrder Object.
        WorkOrder woObj = workorderdetEJBean.getWorkOrderInfo(workorderId);

        // Get the list of Billing Keys for the Billing System.
        String[] blgKeys = workorderdetEJBean.getBillingKeys(customerId, bsId);

        // Release db connection for EJB
        workorderdetEJBean.release();

        // If no Billing Keys for the Billing System selected then redirect
        // to the List Items screen and show the error Message.
        if (blgKeys == null) {
          BlgSys blgsys = new BlgSys();
          Hashtable bSysList = (Hashtable) blgsys.searchBlgSys();
          //	Hashtable bSysList = (Hashtable) USFEnv.getBillSystems();

          // Set the JSP error message
          req.setAttribute("errorMsg", "No BTNs for Billing System " + billSystem);

          // list products for parent WorkOrder Number
          listProducts(workorderId, workorderdetEJBean, session, req, resp);
          return;
        }

        req.setAttribute("prodcredit", "N");
        req.setAttribute("bsystem", String.valueOf(bsId));
        req.setAttribute("bkList", blgKeys);
        req.setAttribute("prodId", formProdId);
        String wid = String.valueOf(workorderId);

        session.putValue("workorderId", wid);

        req.setAttribute("billingsystem", billSystem);

        req.setAttribute("itemname", itemName);

        // Include the JSP to Edit Product
        includeJSP(req, resp, ITEM_JSP_PATH, "editItem");
        return;
      }

      // Button action from JSP is to Edit a Product
      else if (sJSPAction.equals("edit")) {
        String bsysid = req.getParameter("bsId");
        session.putValue("bysysidforedit", bsysid);

        wodId = (new Long((String) req.getParameter("wodId"))).longValue();
        // bkId = (new Long( (String) req.getParameter("bkId"))).longValue() ;

        session.putValue("workorderdetid", String.valueOf(wodId));

        bsId = (new Long((String) req.getParameter("bsId"))).longValue();

        BlgSys blgSys = new BlgSys();
        bsNm = blgSys.getBsName(bsId);

        // Create db connection for EJB
        workorderdetEJBean.connect();

        // WorkOrder woObj = workorderdetEJBean.getWorkOrderInfo(workorderId);

        // Get the WorkOrder Number Object
        WrkOrdrDets wodets_obj = new WrkOrdrDets();
        wodets_obj = workorderdetEJBean.getProductInfo(wodId);

        // Get the List of Billing Keys for the Billing System.
        String[] blgKeys = workorderdetEJBean.getBillingKeys(customerId, bsId);

        // Check if the Item has any Credits. If any credits then Billing
        // Key is not Editable else Editable.
        if (workorderdetEJBean.hasCredits(wodId)) {
          req.setAttribute("prodcredit", "Y");
        } else {
          req.setAttribute("prodcredit", "N");
        }

        // Release db connection for EJB
        workorderdetEJBean.release();

        // If Item Object is not null (which generally is the case) then
        // set the Attributes for the JSP.
        if (wodets_obj != null) {
          // Put the Item Object in session
          editflag = "edit";
          session.putValue("wodets", wodets_obj);
          req.setAttribute("editflag", editflag);

          // Set the attributes for the Billing System, Billing Key List,
          req.setAttribute("bkList", blgKeys);
          req.setAttribute("bsname", bsNm);

          // Include the JSP to Edit the Item.
          includeJSP(req, resp, ITEM_JSP_PATH, "editItem");
          return;
        }

        // If Item Object is null (which generally should not Occur) show
        // the Default page of Item List for the WorkOrder Number
        else {
          // Set the JSP error message
          req.setAttribute(
              "errorMsg", "Product Key - " + wodId + " Information not available in the Data Base");

          // list items for parent WorkOrder Number
          listProducts(workorderId, workorderdetEJBean, session, req, resp);
          return;
        }

      }

      // Button action from JSP is to Delete an Item
      else if (sJSPAction.equals("delete")) {
        String formWodId = req.getParameter("wodId");

        wodId = (new Long((String) req.getParameter("wodId"))).longValue();

        // Create db connection for EJB
        workorderdetEJBean.connect();

        // Delete the Item
        if (workorderdetEJBean.deleteProduct(wodId)) {
          req.setAttribute("errorMsg", "Product Key - " + wodId + " Deleted");
        } else {
          req.setAttribute(
              "errorMsg",
              "Deletion Failed. Product Key - " + wodId + " is associated with amounts.");
        }
        // Release db connection for EJB
        workorderdetEJBean.release();

        // Show the Item List screen
        listProducts(workorderId, workorderdetEJBean, session, req, resp);
        return;

      }

      // Button action from JSP is to Save a Product. This includes Insertion
      // of New Product or Updation of an Existing Product.

      else if (sJSPAction.equals("save")) {
        boolean save = false;
        boolean newProd = false;
        // long qty=0;

        // Read the Billing System Id
        String formBsId = (String) req.getParameter("bs_id");

        String bsysid = (String) req.getParameter("bsysid");
        /*
        String trans_type = (String) req.getParameter("trans_type");

        //String quantity = (String) req.getParameter("qty");
        String quantity="";
        if (!(req.getParameter("qty").equals("")))
        {
        	quantity=(String) req.getParameter("qty");

        	qty = (new Long(quantity).longValue());
        } */
        String prod_stat = (String) req.getParameter("prod_stat");

        double nrcg_dscnt =
            (new Double((String) req.getParameter("NonRecurringDiscount"))).doubleValue();

        double rcg_dscnt =
            (new Double((String) req.getParameter("RecurringDiscount"))).doubleValue();

        String start_month = (String) req.getParameter("strt_month");
        String start_day = (String) req.getParameter("strt_day");
        String start_year = (String) req.getParameter("strt_year");
        String end_month = (String) req.getParameter("end_month");
        String end_day = (String) req.getParameter("end_day");
        String end_year = (String) req.getParameter("end_year");

        String start_date = start_month + "-" + start_day + "-" + start_year;

        String end_date = end_month + "-" + end_day + "-" + end_year;

        long wrkordrid = (new Long((String) session.getValue("WorkOrderId"))).longValue();

        String for_editing = req.getParameter("for_editing");
        String for_new = req.getParameter("for_new");

        String formBkId = (String) req.getParameter("bk_id");

        String formBKId = formBkId.substring(0, formBkId.indexOf("|"));

        String formBTN = formBkId.substring(formBkId.indexOf("|") + 1);

        billkeyId = (new Long(formBKId)).longValue();

        try {
          bsId = (new Long((String) req.getParameter("bs_id"))).longValue();
        } catch (Exception e) {
          USFEnv.getLog().writeDebug("Exception is " + e, this, null);
        }

        RHCCBlgKeys blgkeys = new RHCCBlgKeys();

        if (for_editing.equals("editing")) {
          blgkeys.setRbkId(billkeyId);
          blgkeys.setRbkKeys(formBTN);
          blgkeys.setBsId(new Long(bsysid).longValue());
        }

        if (for_new.equals("new")) {
          blgkeys.setRbkId(billkeyId);
          blgkeys.setRbkKeys(formBTN);
          blgkeys.setBsId(bsId);
        }

        int index = 0;

        WrkOrdrDets wod_obj = new WrkOrdrDets();

        // wod_obj.setTxTyp(trans_type);
        // wod_obj.setQty(qty);
        wod_obj.setNonRcrgDscnt(nrcg_dscnt);
        wod_obj.setRcrgDscnt(rcg_dscnt);
        wod_obj.setRBKID(billkeyId);
        wod_obj.setWodStat(prod_stat);
        wod_obj.setWOID(wrkordrid);

        if (!(start_date.equals(""))) {
          strtDate =
              new java.sql.Date((new SimpleDateFormat("MM-dd-yyyy")).parse(start_date).getTime());
          wod_obj.setStrtDat(strtDate);
        }
        // Else if the Start Date is null update the Item Object Date to
        // null
        else {
          wod_obj.setStrtDat(null);
        }

        // If Item Service End Date is not null read the date and update
        // the Item Object with the date
        if (!(end_date.equals(""))) {
          endDate =
              new java.sql.Date((new SimpleDateFormat("MM-dd-yyyy")).parse(end_date).getTime());
          wod_obj.setEndDat(endDate);
        }
        // Else if the End Date is null update the Item Object Date to null
        else {
          wod_obj.setEndDat(null);
        }

        // Check if the Start Date is after the End Date or equals End Date
        if ((strtDate != null) && (endDate != null) && (strtDate.after(endDate))) {
          prodError = "Product Service Start Date is after Product Service End Date. \n";
          index = 1;
        } else if ((strtDate != null) && (endDate != null) && (strtDate.equals(endDate))) {
          prodError = "Product Service Start Date equals Product Service End Date. \n";
        }

        workorderdetEJBean.connect();

        if (for_editing.equals("editing")) {
          long workorderdetID = (new Long((String) session.getValue("workorderdetid"))).longValue();
          wod_obj.setWODID(workorderdetID);

          if (index == 0) {
            save = workorderdetEJBean.saveProduct(wod_obj);
          }

          if (save) {
            prodError =
                prodError + "<BR> Product Key - " + wod_obj.getWODID() + " Information updated";
            req.setAttribute("error", prodError);
          } else {
            prodError = prodError + "<BR> Failed to update Product Information";
            req.setAttribute("error", prodError);
          }
        }

        if (for_new.equals("new")) {
          if (index == 0) {
            int prodId = Integer.parseInt(req.getParameter("prod_Id"));
            wod_obj.setProd_id(prodId);
            save = workorderdetEJBean.saveProduct(wod_obj);
          }

          if (save) {
            prodError =
                prodError + "<BR> Product Key - " + wod_obj.getWODID() + " Information Saved";
            req.setAttribute("error", prodError);
          } else {
            prodError = prodError + "<BR> Failed to Save Product Information";
            req.setAttribute("error", prodError);
          }
        }

        workorderdetEJBean.release();

        listProducts(wrkordrid, workorderdetEJBean, session, req, resp);
      }

    } // End of try block
    catch (Exception e) {
      if (workorderdetEJBean != null) {
        // calling bean release method
        try {
          workorderdetEJBean.release();
        } catch (Exception ex) {
          USFEnv.getLog().writeCrit(" Exception in calling release() method ", this, e);
        }
      }
      String errorMsg = "Processing Exception in Items Servlet: ";
      USFEnv.getLog().writeCrit(errorMsg, this, e);
      errorJSP(req, resp, errorMsg);
    } // End of catch block
  } // end of doPost()
예제 #24
0
  /**
   * This method returns a <tt>Class</tt> for a helper which can handle the list of distributions
   * specified by <tt>seq1</tt>. We maintain a cache of recently-loaded helpers, so check the cache
   * before going to the trouble of searching for a helper. The cache is blown away every
   * <tt>HELPER_CACHE_REFRESH</tt> seconds.
   *
   * <p>If we can't find a helper in the cache, we must search through the list of available helpers
   * to find an appropriate one. First try to find helper using class sequence as specified by
   * <tt>seq</tt>. Whether or not that succeeds, promote any <tt>Gaussian</tt> in the sequence to
   * <tt>MixGaussians</tt>, and try again. If we get a better match on the second try, return the
   * helper thus found.
   */
  public static Class find_helper_class(Vector seq1, String helper_type)
      throws ClassNotFoundException {
    // Let's see if an appropriate helper is in the cache.
    // If the cache is too old, empty it and search for the helper anew.

    if (System.currentTimeMillis() - cache_timestamp > HELPER_CACHE_REFRESH) {
      helper_cache = new Hashtable();
      cache_timestamp = System.currentTimeMillis();
      // Go on and search for appropriate helper.
    } else {
      HelperCacheKey key = new HelperCacheKey(helper_type, seq1);
      Class helper_class = (Class) helper_cache.get(key);
      if (helper_class != null) {
        if (Global.debug > -1)
          System.err.println(
              "PiHelperLoader.find_helper_class: found helper class: "
                  + helper_class
                  + "; no need to search.");
        return helper_class;
      }
      // else no luck; we have to search for helper.
    }

    // Well, we didn't find a helper in the cache, so let's go to work.
    if (Global.debug > -1)
      System.err.println(
          "PiHelperLoader.find_helper_class: DID NOT FIND HELPER CLASS; NOW SEARCH.");

    Class c1 = null, c2 = null;
    ClassNotFoundException cnfe1 = null, cnfe2 = null;
    int[] class_score1 = new int[1], count_score1 = new int[1];
    int[] class_score2 = new int[1], count_score2 = new int[1];

    try {
      c1 = find_helper_class1(seq1, helper_type, class_score1, count_score1);
    } catch (ClassNotFoundException e) {
      cnfe1 = e;
    } // hang on, we may need to re-throw later.

    Class gaussian_class = Class.forName("riso.distributions.Gaussian");
    MixGaussians mog = new MixGaussians(1, 1);

    Vector seq2 = new Vector(seq1.size());
    for (int i = 0; i < seq1.size(); i++)
      if (gaussian_class.isAssignableFrom((Class) seq1.elementAt(i)))
        seq2.addElement(mog.getClass());
      else seq2.addElement(seq1.elementAt(i));

    try {
      c2 = find_helper_class1(seq2, helper_type, class_score2, count_score2);
    } catch (ClassNotFoundException e) {
      cnfe2 = e;
    }

    if (cnfe1 == null && cnfe2 == null) {
      // Both matched; see which one fits better.
      // Break ties in favor of the helper for non-promoted messages.

      if (class_score1[0] >= class_score2[0]
          || (class_score1[0] == class_score2[0] && count_score1[0] >= count_score2[0])) {
        if (Global.debug > 1)
          System.err.println(
              "\taccept helper " + c1 + " for non-promoted classes instead of " + c2);
        if (Global.debug > 1)
          System.err.println(
              "\t\t"
                  + class_score1[0]
                  + ", "
                  + class_score2[0]
                  + "; "
                  + count_score1[0]
                  + ", "
                  + count_score2[0]);
        helper_cache.put(new HelperCacheKey(helper_type, seq1), c1);
        return c1;
      } else {
        if (Global.debug > 1)
          System.err.println("\taccept helper " + c2 + " for promoted classes instead of " + c1);
        if (Global.debug > 1)
          System.err.println(
              "\t\t"
                  + class_score1[0]
                  + ", "
                  + class_score2[0]
                  + "; "
                  + count_score1[0]
                  + ", "
                  + count_score2[0]);
        helper_cache.put(new HelperCacheKey(helper_type, seq1), c2);
        return c2;
      }
    } else if (cnfe1 == null && cnfe2 != null) {
      // Only the first try matched, return it.
      helper_cache.put(new HelperCacheKey(helper_type, seq1), c1);
      return c1;
    } else if (cnfe1 != null && cnfe2 == null) {
      // Only the second try matched, return it.
      helper_cache.put(new HelperCacheKey(helper_type, seq1), c2);
      return c2;
    } else {
      // Neither try matched. Re-throw the exception generated by the first try.
      throw cnfe1;
    }
  }
예제 #25
0
  /**
   * Contact a belief network context, get the helper list, and search the list to see if there's a
   * helper which matches the type sequence specified. If there's more than one helper which
   * matches, find the ``best fit.''
   *
   * <p>The class and count scores of the best-fitting helper class are written into
   * <tt>max_class_score[0]</tt> and <tt>max_count_score[0]</tt>, respectively.
   */
  public static Class find_helper_class0(
      Vector seq, String helper_type, int[] max_class_score, int[] max_count_score)
      throws ClassNotFoundException {
    long t0 = System.currentTimeMillis();
    if (bnc != null) // make sure the reference is still alive
    try {
        bnc.get_name();
      } catch (RemoteException e) {
        bnc = null;
      }

    if (bnc == null) // need to locate a context
    {
      String cb = System.getProperty("java.rmi.server.codebase", "http://localhost");
      long tt0 = System.currentTimeMillis();
      try {
        bnc = BeliefNetworkContext.locate_context(new URL(cb).getHost());
      } catch (Exception e) {
        throw new ClassNotFoundException("nested: " + e);
      }
    }

    String[] helperlist;
    try {
      helperlist = bnc.get_helper_names(helper_type);
    } catch (RemoteException e) {
      throw new ClassNotFoundException("bnc.get_helper_names failed");
    }

    int[] class_score1 = new int[1], count_score1 = new int[1];
    max_class_score[0] = -1;
    max_count_score[0] = -1;
    Class cmax_score = null;

    for (int i = 0; i < helperlist.length; i++) {
      try {
        Class c = RMIClassLoader.loadClass(helperlist[i]);
        SeqTriple[] sm = (SeqTriple[]) invoke_description(c);
        if (sm == null) continue; // apparently not a helper class
        if (MatchClassPattern.matches(sm, seq, class_score1, count_score1)) {
          if (class_score1[0] > max_class_score[0]
              || (class_score1[0] == max_class_score[0] && count_score1[0] > max_count_score[0])) {
            cmax_score = c;
            max_class_score[0] = class_score1[0];
            max_count_score[0] = count_score1[0];
          }
        }
      } catch (Exception e2) {
        System.err.println("PiHelperLoader: attempt to load " + helperlist[i] + " failed; " + e2);
      }
    }

    if (cmax_score == null) {
      System.err.println("find_helper_class0: failed; helper list:");
      for (int i = 0; i < helperlist.length; i++) System.err.println("\t" + helperlist[i]);

      String s = "";
      for (Enumeration e = seq.elements(); e.hasMoreElements(); ) {
        try {
          Class c = (Class) e.nextElement();
          s += c.getName() + ",";
        } catch (NoSuchElementException ee) {
          s += "???" + ",";
        }
      }

      throw new ClassNotFoundException("no " + helper_type + " helper for sequence [" + s + "]");
    }

    // FOR NOW IGNORE THE POSSIBILITY OF TWO OR MORE MATCHES !!!
    return cmax_score;
  }
예제 #26
0
 protected boolean removeDataFromLog(int xId) {
   int indx = logContains(xId);
   if (indx >= 0) logArray.remove(indx);
   return true;
 }
예제 #27
0
  public static void main(String[] args) {
    boolean do_compile_all = false;
    String bn_name = "", x1_name = "", x2_name = "";
    Vector evidence_names = new Vector();

    for (int i = 0; i < args.length; i++) {
      if (args[i].charAt(0) != '-') continue;

      switch (args[i].charAt(1)) {
        case 'b':
          bn_name = args[++i];
          break;
        case 'a':
          do_compile_all = true;
          break;
        case 'x':
          if (args[i].charAt(2) == '1') x1_name = args[++i];
          else if (args[i].charAt(2) == '2') x2_name = args[++i];
          else System.err.println("PathAnalysis.main: " + args[i] + " -- huh???");
          break;
        case 'e':
          evidence_names.addElement(args[++i]);
          break;
        default:
          System.err.println("PathAnalysis.main: " + args[i] + " -- huh???");
      }
    }

    try {
      BeliefNetworkContext bnc = new BeliefNetworkContext(null);
      bnc.add_path("/bechtel/users10/krarti/dodier/belief-nets/assorted");
      AbstractBeliefNetwork bn = bnc.load_network(bn_name);
      Hashtable path_sets;
      Enumeration p;

      if ((p = PathAnalysis.has_directed_cycle(bn)) == null)
        System.err.println("PathAnalysis: no directed cycles found in " + bn_name);
      else {
        System.err.println("PathAnalysis.main: " + bn_name + " has a directed cycle; quit.");
        System.err.print(" cycle is: ");
        while (p.hasMoreElements()) {
          System.err.print(((AbstractVariable) p.nextElement()).get_name());
          if (p.hasMoreElements()) System.err.print(" -> ");
          else System.err.println("");
        }

        System.exit(1);
      }

      Vector evidence = new Vector();
      if (evidence_names.size() > 0) {
        for (int i = 0; i < evidence_names.size(); i++)
          evidence.addElement(bn.name_lookup((String) (evidence_names.elementAt(i))));
      }

      if (do_compile_all) {
        path_sets = PathAnalysis.compile_all_paths(bn);
      } else {
        AbstractVariable x1 = (AbstractVariable) bn.name_lookup(x1_name);
        AbstractVariable x2 = (AbstractVariable) bn.name_lookup(x2_name);
        path_sets = new Hashtable();
        PathAnalysis.compile_paths(x1, x2, path_sets);

        if (PathAnalysis.are_d_connected(x1, x2, evidence))
          System.err.print(
              x1.get_name() + " and " + x2.get_name() + " are d-connected given evidence ");
        else
          System.err.print(
              x1.get_name() + " and " + x2.get_name() + " are NOT d-connected given evidence ");

        for (int i = 0; i < evidence.size(); i++)
          System.err.print(((AbstractVariable) evidence.elementAt(i)).get_name() + " ");
        System.err.println("");
      }

      System.err.println("PathAnalysis.main: results of path finding:");

      AbstractVariable[] u = bn.get_variables();
      for (int i = 0; i < u.length; i++) {
        System.err.println(" --- paths from: " + u[i].get_name() + " ---");

        for (int j = i + 1; j < u.length; j++) {
          VariablePair vp = new VariablePair(u[i], u[j]);
          Vector path_set = (Vector) path_sets.get(vp);
          if (path_set == null) continue;

          Enumeration path_set_enum = path_set.elements();
          while (path_set_enum.hasMoreElements()) {
            AbstractVariable[] path = (AbstractVariable[]) path_set_enum.nextElement();
            System.err.print(" path: ");
            for (int k = 0; k < path.length; k++) System.err.print(path[k].get_name() + " ");
            System.err.println("");
          }
        }
      }

      System.exit(0);
    } catch (Exception e) {
      System.err.println("PathAnalysis.main:");
      e.printStackTrace();
      System.exit(1);
    }
  }
예제 #28
0
 /**
  * remove a ScalarMapListener
  *
  * @param listener <CODE>ScalarMapListener</CODE> to remove from the list
  */
 public void removeScalarMapListener(ScalarMapListener listener) {
   if (listener != null && ListenerVector != null) {
     ListenerVector.removeElement(listener);
   }
 }