/** @see org.geotools.arcsde.session.ISessionPool#getSession(boolean) */
  public ISession getSession(final boolean transactional)
      throws IOException, UnavailableConnectionException {
    checkOpen();
    try {
      Session connection = null;
      if (transactional) {
        LOGGER.finest("Borrowing session from pool for transactional access");
        connection = (Session) pool.borrowObject();
      } else {
        synchronized (openSessionsNonTransactional) {
          try {
            if (LOGGER.isLoggable(Level.FINER)) {
              LOGGER.finer("Grabbing session from pool on " + Thread.currentThread().getName());
            }
            connection = (Session) pool.borrowObject();
            if (LOGGER.isLoggable(Level.FINER)) {
              LOGGER.finer("Got session from the pool on " + Thread.currentThread().getName());
            }
          } catch (NoSuchElementException e) {
            if (LOGGER.isLoggable(Level.FINER)) {
              LOGGER.finer("No available sessions in the pool, falling back to queued session");
            }
            connection = openSessionsNonTransactional.remove();
          }

          openSessionsNonTransactional.add(connection);

          if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.finer(
                "Got session from the in use queue on " + Thread.currentThread().getName());
          }
        }
      }

      connection.markActive();
      return connection;

    } catch (NoSuchElementException e) {
      LOGGER.log(
          Level.WARNING, "Out of connections: " + e.getMessage() + ". Config: " + this.config);
      throw new UnavailableConnectionException(config.getMaxConnections(), this.config);
    } catch (SeException se) {
      ArcSdeException sdee = new ArcSdeException(se);
      LOGGER.log(Level.WARNING, "ArcSDE error getting connection for " + config, sdee);
      throw sdee;
    } catch (Exception e) {
      LOGGER.log(Level.WARNING, "Unknown problem getting connection: " + e.getMessage(), e);
      throw (IOException)
          new IOException("Unknown problem fetching connection from connection pool").initCause(e);
    }
  }
  protected void doTransform(
      MuleMessage message, String outputEncoding, Source sourceDoc, Result result)
      throws Exception {
    DefaultErrorListener errorListener = new DefaultErrorListener(this);
    javax.xml.transform.Transformer transformer = null;

    try {
      transformer = (javax.xml.transform.Transformer) transformerPool.borrowObject();

      transformer.setErrorListener(errorListener);
      transformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding);

      // set transformation parameters
      if (contextProperties != null) {
        for (Entry<String, Object> parameter : contextProperties.entrySet()) {
          String key = parameter.getKey();
          transformer.setParameter(
              key, evaluateTransformParameter(key, parameter.getValue(), message));
        }
      }

      transformer.transform(sourceDoc, result);

      if (errorListener.isError()) {
        throw errorListener.getException();
      }
    } finally {
      if (transformer != null) {
        transformerPool.returnObject(transformer);
      }
    }
  }
 public Parser get() {
   try {
     return (Parser) pool.borrowObject();
   } catch (Exception e) {
     throw new RuntimeException("Error borrowing a parser from the pool", e);
   }
 }
Exemple #4
0
 @SuppressWarnings("unchecked")
 public T getResource() {
   try {
     return (T) internalPool.borrowObject();
   } catch (Exception e) {
     throw new JedisConnectionException("Could not get a resource from the pool", e);
   }
 }
 public <T> T createProxy(Class<T> serviceClass) {
   NettyClient nettyClient = null;
   try {
     nettyClient = nettyClientPool.borrowObject();
     return nettyClient.createProxy(serviceClass);
   } catch (Exception e) {
     logger.error(e.getMessage(), e);
     throw new NettyException(e.getMessage(), e);
   } finally {
     if (nettyClient != null) {
       try {
         nettyClientPool.returnObject(nettyClient);
       } catch (Exception e) {
         logger.error(e.getMessage(), e);
         throw new NettyException(e.getMessage(), e);
       }
     }
   }
 }
 private static RServices tryBorrowAWorker(int attempts, long wait, TimeUnit timeUnit) {
   for (int i = 0; i < attempts; i++) {
     log.debug("Borrow attempt: {}", i);
     try {
       RServices rServices = (RServices) workerPool.borrowObject();
       log.debug("Borrowed {} from the pool", rServices.getServantName());
       return rServices;
     } catch (TimeoutException e) {
       log.debug("RServices pool is probably busy..", e);
       log.info("No free workers in the pool currently. Waiting for {} {}...", wait, timeUnit);
     } catch (Exception e) {
       log.error("Failed to borrow RServices worker", e);
       return null;
     }
     waitFor(timeUnit.toMillis(wait));
   }
   log.error("Could not borrow RServices after " + attempts + " attempts");
   return null;
 }
    @SuppressWarnings("unchecked")
    public Void call() throws Exception {
      // LOG.debug("ORIGIN " + origin);
      int oi = stopIndices.get(origin); // origin index
      // first check for walking transfers
      // LOG.debug("    Walk");

      BinHeap<State> heap;
      try {
        heap = (BinHeap<State>) heapPool.borrowObject();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }

      BasicShortestPathTree spt = new BasicShortestPathTree(500000);
      State s0 = new State(origin, options);
      spt.add(s0);
      heap.insert(s0, s0.getWeight());
      while (!heap.empty()) {
        double w = heap.peek_min_key();
        State u = heap.extract_min();
        if (!spt.visit(u)) continue;
        Vertex uVertex = u.getVertex();
        // LOG.debug("heap extract " + u + " weight " + w);
        if (w > MAX_WEIGHT) break;
        if (uVertex instanceof TransitStop) {
          int di = stopIndices.get(uVertex); // dest index
          table[oi][di] = (float) w;
          // LOG.debug("    Dest " + u + " w=" + w);
        }
        for (Edge e : uVertex.getOutgoing()) {
          if (!(e instanceof PreBoardEdge)) {
            State v = e.optimisticTraverse(u);
            if (v != null && spt.add(v)) heap.insert(v, v.getWeight());
          }
        }
      }

      // then check what is accessible in one transit trip
      heap.reset(); // recycle heap
      spt = new BasicShortestPathTree(50000);
      // first handle preboard edges
      Queue<Vertex> q = new ArrayDeque<Vertex>(100);
      q.add(origin);
      while (!q.isEmpty()) {
        Vertex u = q.poll();
        for (Edge e : u.getOutgoing()) {
          if (e instanceof PatternBoard) {
            Vertex v = ((PatternBoard) e).getToVertex();
            // give onboard vertices same index as their
            // corresponding station
            stopIndices.put(v, oi);
            StateEditor se = (new State(u, options)).edit(e);
            se.incrementWeight(OPTIMISTIC_BOARD_COST);
            s0 = se.makeState();
            spt.add(s0);
            heap.insert(s0, s0.getWeight());
            // _log.debug("    board " + tov);
          } else if (e instanceof FreeEdge) { // handle preboard
            Vertex v = ((FreeEdge) e).getToVertex();
            // give onboard vertices same index as their
            // corresponding station
            stopIndices.put(v, oi);
            q.add(v);
          }
        }
      }
      // all boarding edges for this stop have now been traversed
      // LOG.debug("    Transit");
      while (!heap.empty()) {
        // check for transit stops when pulling off of heap
        // and continue when one is found
        // this is enough to prevent reboarding
        // need to mark closed vertices because otherwise cycles may
        // appear (interlining...)
        double w = heap.peek_min_key();
        State u = heap.extract_min();
        if (!spt.visit(u)) continue;
        // LOG.debug("    Extract " + u + " w=" + w);
        Vertex uVertex = u.getVertex();
        if (uVertex instanceof TransitStop) {
          int di = stopIndices.get(uVertex); // dest index
          if (table[oi][di] > w) {
            table[oi][di] = (float) w;
            // LOG.debug("    Dest " + u + "w=" + w);
          }
          continue;
        }
        for (Edge e : uVertex.getOutgoing()) {
          // LOG.debug("        Edge " + e);
          State v = e.optimisticTraverse(u);
          if (v != null && spt.add(v)) heap.insert(v, v.getWeight());
          // else LOG.debug("        (skip)");
        }
      }
      heapPool.returnObject(heap);
      incrementCount();
      return null;
    }
  /**
   * Creates a new SessionPool object for the given config.
   *
   * @param config holds connection options such as server, user and password, as well as tuning
   *     options as maximum number of connections allowed
   * @throws IOException If connection could not be established
   * @throws NullPointerException If config is null
   */
  protected SessionPool(ArcSDEConnectionConfig config) throws IOException {
    if (config == null) {
      throw new NullPointerException("parameter config can't be null");
    }

    this.config = config;
    LOGGER.fine("populating ArcSDE connection pool");

    this.seConnectionFactory = createConnectionFactory();

    final int minConnections = config.getMinConnections().intValue();
    final int maxConnections = config.getMaxConnections().intValue();
    if (minConnections > maxConnections) {
      throw new IllegalArgumentException("pool.minConnections > pool.maxConnections");
    }
    { // configure connection pool
      Config poolCfg = new Config();
      // pool upper limit
      poolCfg.maxActive = config.getMaxConnections().intValue();

      // minimum number of idle objects. MAKE SURE this is 0, otherwise the pool will start
      // trying to create connections permanently even if there's a connection failure,
      // ultimately leading to the exhaustion of resources
      poolCfg.minIdle = 0;

      // how many connections may be idle at any time? -1 = no limit. We're running an
      // eviction thread to take care of idle connections (see minEvictableIdleTimeMillis and
      // timeBetweenEvictionRunsMillis)
      poolCfg.maxIdle = -1;

      // When reached the pool upper limit, block and wait for an idle connection for maxWait
      // milliseconds before failing
      poolCfg.maxWait = config.getConnTimeOut().longValue();
      if (poolCfg.maxWait > 0) {
        poolCfg.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
      } else {
        poolCfg.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
      }

      // check connection health at borrowObject()?
      poolCfg.testOnBorrow = true;
      // check connection health at returnObject()?
      poolCfg.testOnReturn = false;
      // check periodically the health of idle connections and discard them if can't be
      // validated?
      poolCfg.testWhileIdle = false;

      // check health of idle connections every 30 seconds
      // /poolCfg.timeBetweenEvictionRunsMillis = 30000;

      // drop connections that have been idle for at least 5 minutes
      poolCfg.minEvictableIdleTimeMillis = 5 * 60 * 1000;

      pool = new GenericObjectPool(seConnectionFactory, poolCfg);

      LOGGER.fine("Created ArcSDE connection pool for " + config);
    }

    ISession[] preload = new ISession[minConnections];

    try {
      for (int i = 0; i < minConnections; i++) {
        preload[i] = (ISession) pool.borrowObject();
        if (i == 0) {
          SeRelease seRelease = preload[i].getRelease();
          String sdeDesc = seRelease.getDesc();
          int major = seRelease.getMajor();
          int minor = seRelease.getMinor();
          int bugFix = seRelease.getBugFix();
          String desc = "ArcSDE " + major + "." + minor + "." + bugFix + " " + sdeDesc;
          LOGGER.fine("Connected to " + desc);
        }
      }

      for (int i = 0; i < minConnections; i++) {
        pool.returnObject(preload[i]);
      }
    } catch (Exception e) {
      close();
      if (e instanceof IOException) {
        throw (IOException) e;
      }
      throw (IOException) new IOException().initCause(e);
    }
  }
 @Before
 public void setup() throws Exception {
   mService.setMessagePusher(mMessagePusher);
   when(mPool.borrowObject()).thenReturn(mConnection);
 }
Exemple #10
0
  /**
   * TODO time out is actually double as it waits for the producer and then waits for the response.
   * Use an atomic long to manage the countdown
   */
  @Override
  public void sendMessage(
      final Exchange exchange,
      final AsyncCallback callback,
      final MessageProducerResources producer,
      final ReleaseProducerCallback releaseProducerCallback)
      throws Exception {
    Message request = getEndpoint().getBinding().makeJmsMessage(exchange, producer.getSession());

    String correlationId =
        exchange.getIn().getHeader(JmsConstants.JMS_CORRELATION_ID, String.class);
    if (correlationId == null) {
      // we append the 'Camel-' prefix to know it was generated by us
      correlationId = GENERATED_CORRELATION_ID_PREFIX + getUuidGenerator().generateUuid();
    }

    Object responseObject = null;
    Exchanger<Object> messageExchanger = new Exchanger<Object>();
    JmsMessageHelper.setCorrelationId(request, correlationId);
    EXCHANGERS.put(correlationId, messageExchanger);

    MessageConsumerResources consumer = consumers.borrowObject();
    JmsMessageHelper.setJMSReplyTo(request, consumer.getReplyToDestination());
    consumers.returnObject(consumer);
    producer.getMessageProducer().send(request);

    // Return the producer to the pool so another waiting producer
    // can move forward
    // without waiting on us to complete the exchange
    try {
      releaseProducerCallback.release(producer);
    } catch (Exception exception) {
      // thrown if the pool is full. safe to ignore.
    }

    try {
      responseObject = messageExchanger.exchange(null, getResponseTimeOut(), TimeUnit.MILLISECONDS);
      EXCHANGERS.remove(correlationId);
    } catch (InterruptedException e) {
      log.debug("Exchanger was interrupted while waiting on response", e);
      exchange.setException(e);
    } catch (TimeoutException e) {
      log.debug("Exchanger timed out while waiting on response", e);
      exchange.setException(e);
    }

    if (exchange.getException() == null) {
      if (responseObject instanceof Throwable) {
        exchange.setException((Throwable) responseObject);
      } else if (responseObject instanceof Message) {
        Message message = (Message) responseObject;

        SjmsMessage response =
            new SjmsMessage(message, consumer.getSession(), getEndpoint().getBinding());
        // the JmsBinding is designed to be "pull-based": it will populate the Camel message on
        // demand
        // therefore, we link Exchange and OUT message before continuing, so that the JmsBinding has
        // full access
        // to everything it may need, and can populate headers, properties, etc. accordingly (solves
        // CAMEL-6218).
        exchange.setOut(response);
      } else {
        exchange.setException(new CamelException("Unknown response type: " + responseObject));
      }
    }

    callback.done(isSynchronous());
  }