public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo cri)
      throws javax.resource.ResourceException {
    if (xadsSelector == null) {
      return getXAManagedConnection(subject, cri);
    }

    // try to get a connection as many times as many urls we have in the list
    for (int i = 0; i < xadsSelector.getCustomSortedUrls().size(); ++i) {
      XAData xaData = (XAData) xadsSelector.getUrlObject();

      if (log.isTraceEnabled()) {
        log.trace("Trying to create an XA connection to " + xaData.url);
      }

      try {
        return getXAManagedConnection(subject, cri);
      } catch (ResourceException e) {
        log.warn("Failed to create an XA connection to " + xaData.url + ": " + e.getMessage());
        xadsSelector.failedUrlObject(xaData);
      }
    }

    // we have supposedly tried all the urls
    throw new JBossResourceException(
        "Could not create connection using any of the URLs: " + xadsSelector.getAllUrlObjects());
  }
 /* JSF navigation method (from trade.xhtml) */
 public String disconnect() {
   infoBox = "";
   try {
     connection.close();
     connection = null;
   } catch (ResourceException e) {
     log.info(e.getMessage());
   }
   return "index";
 }
 /* JSF navigation method (from index.xhtml) */
 public String connect() {
   String page = "index";
   if (connection == null) {
     try {
       log.info("[ResourceAccessBean] Getting connection from the RA");
       connection = connectionFactory.getConnection();
       page = "trade";
     } catch (ResourceException e) {
       log.info(e.getMessage());
     }
   }
   return page;
 }
 /**
  * Second version of the <code>execute</code> methods.<br>
  * <br>
  * This method returns <code>false</code>, if the request does not match according to the contract
  * of {@link #canHandle}. This never happens under normal conditions since the {@link
  * InteractionHandler} does not call <code>execute</code>, if {@link #canHandle} returns <code>
  * false</code>. <br>
  * <br>
  * Otherwise, this method fills the response <code>Record</code> with the specified response
  * <code>Map</code> data. Use the <code>setResponse</code> methods that take a <code>Map</code> to
  * prepare the response <code>Map</code>. The response <code>Record</code> must implement <code>
  * MappedRecord</code> (it does, otherwise the request would have been rejected by {@link
  * #canHandle}). If no response <code>Map</code> is specified at all, the response <code>Record
  * </code> is not touched but <code>true</code> is returned anyway
  *
  * @param interactionSpec the interaction spec
  * @param actualRequest the actual request
  * @param actualResponse the actual response
  * @return <code>true</code> under normal conditions
  */
 public boolean execute(
     InteractionSpec interactionSpec, Record actualRequest, Record actualResponse)
     throws ResourceException {
   if (!canHandle(interactionSpec, actualRequest, actualResponse)) return false;
   try {
     if (null != responseData && null != actualResponse) {
       ((MappedRecord) actualResponse).clear();
       ((MappedRecord) actualResponse).putAll(responseData);
     }
   } catch (Exception exc) {
     ResourceException resExc = new ResourceException("execute() failed");
     resExc.setLinkedException(exc);
     throw resExc;
   }
   return true;
 }
  /*
   * @see com.atomikos.datasource.xa.XATransactionalResource#refreshXAConnection()
   */
  protected XAResource refreshXAConnection() throws ResourceException {
    if (LOGGER.isInfoEnabled()) {
      LOGGER.logInfo("refreshXAConnection() for resource: " + getName());
    }

    XAResource ret = null;
    if (connection != null) {
      try {
        connection.destroy();
      } catch (Exception normal) {
        // this can be expected, since this method is only called
        // if there is a connection problem
      }
    }

    try {

      LOGGER.logInfo("about to block for new connection...");
      // System.out.println ( "ABOUT TO BLOCK FOR NEW CONNECTION");
      connection = mcf.createManagedConnection(null, null);

    } catch (javax.resource.ResourceException e) {
      // ignore and return null: happens if resource is down
      // at this moment
      connection = null;
    } finally {
      // System.out.println ( "BLOCKING DONE");
      if (LOGGER.isInfoEnabled()) {
        LOGGER.logInfo("blocking done.");
      }
    }

    try {
      if (connection != null) ret = connection.getXAResource();
    } catch (javax.resource.ResourceException e) {
      LOGGER.logWarning("error getting XAResource: " + e.getMessage());

      throw new ResourceException("Error in getting XA resource", e);
    }

    LOGGER.logInfo("refreshXAConnection() done.");

    // System.out.println ( "DONE REFRESHXACONNECTION FOR RESOURCE: " +
    // getName() );

    return ret;
  }
 /**
  * First version of the <code>execute</code> methods.<br>
  * <br>
  * This method returns <code>null</code>, if the request does not match according to the contract
  * of {@link #canHandle}. This never happens under normal conditions since the {@link
  * InteractionHandler} does not call <code>execute</code>, if {@link #canHandle} returns <code>
  * false</code>. <br>
  * <br>
  * Otherwise, this method returns the specified response. If a response <code>Record</code> object
  * is specified (use {@link #setResponse(Record)}), it always takes precedence, i.e. the response
  * <code>Map</code> will be ignored. If no <code>Record</code> object is specified, a <code>Record
  * </code> object is created and filled with the specified response <code>Map</code> data. Use the
  * <code>setResponse</code> methods that take a <code>Map</code> to prepare the response <code>Map
  * </code>. The created <code>Record</code> is of the the specified type (the <code>setResponse
  * </code> method that takes a second <code>Class</code> parameter allows for specifying a type).
  * If no type is specified, a {@link com.mockrunner.mock.connector.cci.MockMappedRecord} is
  * created. If no response <code>Map</code> is specified at all, an empty {@link
  * com.mockrunner.mock.connector.cci.MockMappedRecord} will be returned.
  *
  * @param interactionSpec the interaction spec
  * @param actualRequest the actual request
  * @return the response according to the current request
  */
 public Record execute(InteractionSpec interactionSpec, Record actualRequest)
     throws ResourceException {
   if (!canHandle(interactionSpec, actualRequest, null)) return null;
   if (null != responseRecord) return responseRecord;
   MappedRecord response = null;
   try {
     if (null == responseClass) {
       response = new MockMappedRecord();
     } else {
       response = (MappedRecord) responseClass.newInstance();
     }
     if (null != responseData) {
       response.putAll(responseData);
     }
   } catch (Exception exc) {
     ResourceException resExc = new ResourceException("execute() failed");
     resExc.setLinkedException(exc);
     throw resExc;
   }
   return (Record) response;
 }
  /** Returns true for a valid connection. */
  boolean isValid(Subject subject, ConnectionRequestInfo requestInfo, UserPoolItem userPoolItem) {
    try {
      ManagedConnection mConn = getManagedConnection();

      if (mConn == null) return false;

      Object userConn = userPoolItem.getUserConnection();

      if (userConn == null) {
        userConn = mConn.getConnection(subject, requestInfo);

        userPoolItem.setUserConnection(userConn);
      }

      return userConn != null;
    } catch (ResourceException e) {
      log.log(Level.WARNING, e.toString(), e);

      return false;
    }
  }
 /** Output records are not supported/required. */
 public boolean execute(InteractionSpec spec, Record input, Record output)
     throws ResourceException {
   if (!(spec instanceof MongoInteractionSpec)) {
     throw EISException.invalidInteractionSpecType();
   }
   if (!(input instanceof MongoRecord) || !(output instanceof MongoRecord)) {
     throw EISException.invalidRecordType();
   }
   MongoInteractionSpec mongoSpec = (MongoInteractionSpec) spec;
   MongoRecord record = (MongoRecord) input;
   MongoRecord translationRecord = (MongoRecord) output;
   MongoOperation operation = mongoSpec.getOperation();
   String collectionName = mongoSpec.getCollection();
   if (operation == null) {
     throw new ResourceException("Mongo operation must be set");
   }
   if (collectionName == null) {
     throw new ResourceException("DB Collection name must be set");
   }
   try {
     DBCollection collection = this.connection.getDB().getCollection(collectionName);
     DBObject object = buildDBObject(record);
     DBObject translation = buildDBObject(translationRecord);
     if (operation == MongoOperation.UPDATE) {
       WriteResult result =
           collection.update(translation, object, mongoSpec.isUpsert(), mongoSpec.isMulti());
       return result.getN() > 0;
     } else {
       throw new ResourceException("Invalid operation: " + operation);
     }
   } catch (Exception exception) {
     ResourceException resourceException = new ResourceException(exception.toString());
     resourceException.initCause(exception);
     throw resourceException;
   }
 }
  /**
   * Execute the interaction and return output record. The spec is either GET, PUT or DELETE
   * interaction.
   */
  public Record execute(InteractionSpec spec, Record record) throws ResourceException {
    if (!(spec instanceof MongoInteractionSpec)) {
      throw EISException.invalidInteractionSpecType();
    }
    if (!(record instanceof MongoRecord)) {
      throw EISException.invalidRecordType();
    }
    MongoInteractionSpec mongoSpec = (MongoInteractionSpec) spec;
    MongoRecord input = (MongoRecord) record;
    MongoOperation operation = mongoSpec.getOperation();
    String collectionName = mongoSpec.getCollection();
    if (operation == null) {
      ResourceException resourceException = new ResourceException("Mongo operation must be set");
      throw resourceException;
    }
    if (operation == MongoOperation.EVAL) {
      Object result = this.connection.getDB().eval(mongoSpec.getCode());
      return buildRecordFromDBObject((DBObject) result);
    }
    if (collectionName == null) {
      ResourceException resourceException = new ResourceException("DB Collection name must be set");
      throw resourceException;
    }
    try {
      DBCollection collection = this.connection.getDB().getCollection(collectionName);
      if (mongoSpec.getOptions() > 0) {
        collection.setOptions(mongoSpec.getOptions());
      }
      if (mongoSpec.getReadPreference() != null) {
        collection.setReadPreference(mongoSpec.getReadPreference());
      }
      if (mongoSpec.getWriteConcern() != null) {
        collection.setWriteConcern(mongoSpec.getWriteConcern());
      }
      if (operation == MongoOperation.INSERT) {
        DBObject object = buildDBObject(input);
        collection.insert(object);
      } else if (operation == MongoOperation.REMOVE) {
        DBObject object = buildDBObject(input);
        collection.remove(object);
      } else if (operation == MongoOperation.FIND) {
        DBObject sort = null;
        if (input.containsKey(MongoRecord.SORT)) {
          sort = buildDBObject((MongoRecord) input.get(MongoRecord.SORT));
          input.remove(MongoRecord.SORT);
        }
        DBObject select = null;
        if (input.containsKey("$select")) {
          select = buildDBObject((MongoRecord) input.get("$select"));
          input.remove("$select");
        }
        DBObject object = buildDBObject(input);
        DBCursor cursor = collection.find(object, select);
        if (sort != null) {
          cursor.sort(sort);
        }
        try {
          if (mongoSpec.getSkip() > 0) {
            cursor.skip(mongoSpec.getSkip());
          }
          if (mongoSpec.getLimit() != 0) {
            cursor.limit(mongoSpec.getLimit());
          }
          if (mongoSpec.getBatchSize() != 0) {
            cursor.batchSize(mongoSpec.getBatchSize());
          }
          if (!cursor.hasNext()) {
            return null;
          }
          MongoListRecord results = new MongoListRecord();
          while (cursor.hasNext()) {
            DBObject result = cursor.next();
            results.add(buildRecordFromDBObject(result));
          }
          return results;
        } finally {
          cursor.close();
        }

      } else {
        throw new ResourceException("Invalid operation: " + operation);
      }
    } catch (Exception exception) {
      ResourceException resourceException = new ResourceException(exception.toString());
      resourceException.initCause(exception);
      throw resourceException;
    }
    return null;
  }