Example #1
0
  public boolean beforeInsert(ObjectRepresentation objectRepresentation) {
    String className = objectRepresentation.getObjectClassName();

    // The mutex is used to avoid concurrent access for this operation
    Mutex mutex = MutexFactory.get("SEQUENCE_MUTEX_[" + className + "]");

    System.out.print("SequenceTrigger called by " + className);

    OID oid = objectRepresentation.getOid();

    if (oid != null) {
      System.out.print(" (" + oid.oidToString() + ") ");
    } else {
      System.out.print(" (No OID) ");
    }

    try {
      Long existingId = null;

      try {
        existingId = (Long) objectRepresentation.getValueOf("id");
      } catch (Exception e) {
        e.printStackTrace();

        System.out.print(" which failed the objectRepresentation.getValueOf('id');");

        return false;
      }

      if (existingId == null) {
        // Acquire the trigger
        mutex.acquire("SEQUENCE_TRIGGER_[" + className + "]");

        long id = getNextId(className);

        // Sets the value on the user object
        objectRepresentation.setValueOf("id", new Long(id));

        System.out.println(" which got the ID " + id);

        return true;
      } else {
        System.out.println(" which already got the ID " + existingId);
      }
    } catch (Exception e) {
      e.printStackTrace();

      throw new RuntimeException("Error in SequenceTrigger. Code should be improved.", e);
    } finally {
      // Release the mutex
      if (mutex != null && mutex.isInUse()) {
        mutex.release("SEQUENCE_TRIGGER_[" + className + "]");
      }
    }

    return false;
  }