public Map<String, Object>[] listMessages(final String filterStr) throws Exception {
    checkStarted();

    clearIO();
    try {
      Filter filter = FilterImpl.createFilter(filterStr);
      List<Map<String, Object>> messages = new ArrayList<Map<String, Object>>();
      queue.flushExecutor();
      LinkedListIterator<MessageReference> iterator = queue.iterator();
      try {
        while (iterator.hasNext()) {
          MessageReference ref = iterator.next();
          if (filter == null || filter.match(ref.getMessage())) {
            Message message = ref.getMessage();
            messages.add(message.toMap());
          }
        }
        return messages.toArray(new Map[messages.size()]);
      } finally {
        iterator.close();
      }
    } catch (HornetQException e) {
      throw new IllegalStateException(e.getMessage());
    } finally {
      blockOnIO();
    }
  }
  public void write(
      final long position,
      final long size,
      final ByteBuffer directByteBuffer,
      final AIOCallback aioCallback) {
    if (aioCallback == null) {
      throw new NullPointerException("Null Callback");
    }

    checkOpened();
    if (poller == null) {
      startPoller();
    }

    pendingWrites.countUp();

    if (writeExecutor != null) {
      maxIOSemaphore.acquireUninterruptibly();

      writeExecutor.execute(
          new Runnable() {
            public void run() {
              long sequence = nextWritingSequence.getAndIncrement();

              try {
                write(handler, sequence, position, size, directByteBuffer, aioCallback);
              } catch (HornetQException e) {
                callbackError(
                    aioCallback, sequence, directByteBuffer, e.getType().getCode(), e.getMessage());
              } catch (RuntimeException e) {
                callbackError(
                    aioCallback,
                    sequence,
                    directByteBuffer,
                    HornetQExceptionType.INTERNAL_ERROR.getCode(),
                    e.getMessage());
              }
            }
          });
    } else {
      maxIOSemaphore.acquireUninterruptibly();

      long sequence = nextWritingSequence.getAndIncrement();

      try {
        write(handler, sequence, position, size, directByteBuffer, aioCallback);
      } catch (HornetQException e) {
        callbackError(
            aioCallback, sequence, directByteBuffer, e.getType().getCode(), e.getMessage());
      } catch (RuntimeException e) {
        callbackError(
            aioCallback,
            sequence,
            directByteBuffer,
            HornetQExceptionType.INTERNAL_ERROR.getCode(),
            e.getMessage());
      }
    }
  }
 public void testCreateConsumerNoQ() throws Exception {
   try {
     clientSession.createConsumer(queueName);
     Assert.fail("should throw exception");
   } catch (NonExistentQueueException neqe) {
     // ok
   } catch (HornetQException e) {
     fail("Invalid Exception type:" + e.getType());
   }
 }
 public void testCreateConsumerWithInvalidFilter() throws Exception {
   clientSession.createQueue(queueName, queueName, false);
   try {
     clientSession.createConsumer(queueName, "this is not valid filter");
     Assert.fail("should throw exception");
   } catch (InvalidFilterExpressionException ifee) {
     // ok
   } catch (HornetQException e) {
     fail("Invalid Exception type:" + e.getType());
   }
 }
  public boolean removeMessage(final long messageID) throws Exception {
    checkStarted();

    clearIO();
    try {
      return queue.deleteReference(messageID);
    } catch (HornetQException e) {
      throw new IllegalStateException(e.getMessage());
    } finally {
      blockOnIO();
    }
  }
 public void writeInternal(long positionToWrite, long size, ByteBuffer bytes)
     throws HornetQException {
   try {
     writeInternal(handler, positionToWrite, size, bytes);
   } catch (HornetQException e) {
     fireExceptionListener(e.getType().getCode(), e.getMessage());
     throw e;
   }
   if (bufferCallback != null) {
     bufferCallback.bufferDone(bytes);
   }
 }
Exemple #7
0
 private void init() throws YamcsApiException {
   try {
     String username = null;
     String password = null;
     if (invm) {
       locator =
           HornetQClient.createServerLocatorWithoutHA(
               new TransportConfiguration(Protocol.IN_VM_FACTORY));
       sessionFactory = locator.createSessionFactory();
       username = hornetqInvmUser;
       password = hornetqInvmPass;
     } else {
       if (ycd.host != null) {
         Map<String, Object> tcpConfig = new HashMap<String, Object>();
         tcpConfig.put(TransportConstants.HOST_PROP_NAME, ycd.host);
         tcpConfig.put(TransportConstants.PORT_PROP_NAME, ycd.port);
         locator =
             HornetQClient.createServerLocatorWithoutHA(
                 new TransportConfiguration(NettyConnectorFactory.class.getName(), tcpConfig));
         sessionFactory = locator.createSessionFactory();
       } else {
         locator =
             HornetQClient.createServerLocatorWithoutHA(
                 new TransportConfiguration(NettyConnectorFactory.class.getName()));
         sessionFactory = locator.createSessionFactory();
       }
       username = ycd.username;
       password = ycd.password;
     }
     // All sessions are authenticated, a null username translates to
     // guest auth and authz (if allowed by server)
     session =
         sessionFactory.createSession(username, password, false, true, true, preAcknowledge, 1);
     session.start();
   } catch (HornetQException e) {
     // Pass specific HornetQExceptions as our cause, helps identify
     // permissions problems
     try {
       close();
     } catch (HornetQException e1) {
     }
     throw new YamcsApiException(e.getMessage(), e);
   } catch (Exception e) {
     // Pass Exception's cause as our cause.
     System.out.println(e);
     // close everything
     try {
       close();
     } catch (HornetQException e1) {
     }
     throw new YamcsApiException(e.getMessage(), e.getCause());
   }
 }
  @Test
  public void testSessionClosedOnRemotingConnectionFailure() throws Exception {
    ClientSession session = addClientSession(sf.createSession());

    session.createQueue("fooaddress", "fooqueue");

    ClientProducer prod = session.createProducer("fooaddress");

    ClientConsumer cons = session.createConsumer("fooqueue");

    session.start();

    prod.send(session.createMessage(false));

    Assert.assertNotNull(cons.receive());

    // Now fail the underlying connection

    RemotingConnection connection = ((ClientSessionInternal) session).getConnection();

    connection.fail(new HornetQNotConnectedException());

    Assert.assertTrue(session.isClosed());

    Assert.assertTrue(prod.isClosed());

    Assert.assertTrue(cons.isClosed());

    // Now try and use the producer

    try {
      prod.send(session.createMessage(false));

      Assert.fail("Should throw exception");
    } catch (HornetQObjectClosedException oce) {
      // ok
    } catch (HornetQException e) {
      fail("Invalid Exception type:" + e.getType());
    }

    try {
      cons.receive();

      Assert.fail("Should throw exception");
    } catch (HornetQObjectClosedException oce) {
      // ok
    } catch (HornetQException e) {
      fail("Invalid Exception type:" + e.getType());
    }

    session.close();
  }
  public int expireMessages(final String filterStr) throws Exception {
    checkStarted();

    clearIO();
    try {
      Filter filter = FilterImpl.createFilter(filterStr);
      return queue.expireReferences(filter);
    } catch (HornetQException e) {
      throw new IllegalStateException(e.getMessage());
    } finally {
      blockOnIO();
    }
  }
Exemple #10
0
 public void connectionFailed(HornetQException e, boolean failedOver) {
   if (failedOver) {
     logger.info("reconnected to yamcs: {}", e.getMessage());
     for (ConnectionListener cl : connectionListeners) {
       cl.connected(connParams.getUrl());
     }
   } else {
     logger.warn("connection to yamcs failed: {}", e.getMessage());
     for (ConnectionListener cl : connectionListeners) {
       cl.connectionFailed(connParams.getUrl(), new YamcsException(e.getMessage(), e));
       cl.log(e.getMessage());
     }
   }
 }
Exemple #11
0
 public void testConnectIntoNonBackup() throws Exception {
   setupServer(false);
   try {
     ClientSessionFactory sf = createSessionFactory(locator);
     manager = new ReplicationManager(sf.getConnection(), factory);
     addHornetQComponent(manager);
     manager.start();
     Assert.fail("Exception was expected");
   } catch (NotConnectedException nce) {
     // ok
   } catch (HornetQException expected) {
     fail("Invalid Exception type:" + expected.getType());
   }
 }
 private void run() {
   try {
     if (HornetQServerLogger.LOGGER.isDebugEnabled()) {
       HornetQServerLogger.LOGGER.debug("deleting temporary queue " + bindingName);
     }
     try {
       server.destroyQueue(bindingName, null, false);
     } catch (HornetQException e) {
       // that's fine.. it can happen due to queue already been deleted
       HornetQServerLogger.LOGGER.debug(e.getMessage(), e);
     }
   } catch (Exception e) {
     HornetQServerLogger.LOGGER.errorRemovingTempQueue(e, bindingName);
   }
 }
  public void testSSLWithIncorrectKeyStorePassword() throws Exception {
    tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
    tc.getParams()
        .put(TransportConstants.KEYSTORE_PATH_PROP_NAME, TransportConstants.DEFAULT_KEYSTORE_PATH);
    tc.getParams().put(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, "invalid password");

    ServerLocator locator = addServerLocator(HornetQClient.createServerLocatorWithoutHA(tc));
    try {
      ClientSessionFactory sf = createSessionFactory(locator);
      Assert.fail();
    } catch (HornetQNotConnectedException se) {
      // ok
    } catch (HornetQException e) {
      fail("Invalid Exception type:" + e.getType());
    }
  }
  // see https://jira.jboss.org/jira/browse/HORNETQ-234
  public void testPlainConnectionToSSLEndpoint() throws Exception {
    tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, false);

    ServerLocator locator = addServerLocator(HornetQClient.createServerLocatorWithoutHA(tc));
    locator.setCallTimeout(2000);
    try {
      createSessionFactory(locator);
      fail("expecting exception");
    } catch (HornetQNotConnectedException se) {
      // ok
    } catch (HornetQConnectionTimedOutException ctoe) {
      // ok
    } catch (HornetQException e) {
      fail("Invalid Exception type:" + e.getType());
    }
  }
Exemple #15
0
  public void beforeReconnect(HornetQException e) {
    logger.warn("disconnected from yamcs: {}", e.getMessage());
    for (ConnectionListener cl : connectionListeners) {
      cl.disconnected();
      cl.log(e.getMessage());
    }

    // clear all pending messages in the data consumers, as they will be re-submitted
    // by yamcs upon re-connect
    for (ClientConsumer consumer : dataConsumers) {
      try {
        MessageHandler handler = consumer.getMessageHandler();
        if (handler instanceof ClientAckMessageHandler) {
          ((ClientAckMessageHandler) handler).clearPendingMessages();
        }
      } catch (HornetQException e1) {
        // ignore
      }
    }
  }
 /* (non-Javadoc)
  * @see org.hornetq.core.remoting.FailureListener#connectionFailed(org.hornetq.api.core.HornetQException, boolean)
  */
 public void connectionFailed(HornetQException exception, boolean failedOver) {
   if (exception.getType() == HornetQExceptionType.DISCONNECTED) {
     HornetQJMSLogger.LOGGER.warn("being disconnected for server shutdown", exception);
   } else {
     HornetQJMSLogger.LOGGER.warn(
         "Notified of connection failure in xa discovery, we will retry on the next recovery",
         exception);
   }
   internalStop();
   HornetQRecoveryRegistry.getInstance().failedDiscovery(this);
 }
Exemple #17
0
 private void decideOnAction() {
   // we may get called via multiple paths so need to guard
   synchronized (decisionGuard) {
     if (signal == BACKUP_ACTIVATION.FAIL_OVER) {
       return;
     }
     if (!isLiveDown()) {
       try {
         // no point in repeating all the reconnection logic
         sessionFactory.connect(RECONNECT_ATTEMPTS, false);
         return;
       } catch (HornetQException e) {
         if (e.getType() != HornetQExceptionType.NOT_CONNECTED)
           HornetQServerLogger.LOGGER.errorReConnecting(e);
       }
     }
     // live is assumed to be down, backup fails-over
     signal = BACKUP_ACTIVATION.FAIL_OVER;
   }
   latch.countDown();
 }
 public void testCreateConsumerNoQ() throws Exception {
   HornetQServer service = createServer(false);
   try {
     service.start();
     ClientSessionFactory cf = createInVMFactory();
     cf.setProducerMaxRate(99);
     cf.setBlockOnNonDurableSend(true);
     cf.setBlockOnNonDurableSend(true);
     ClientSessionInternal clientSession =
         (ClientSessionInternal) cf.createSession(false, true, true);
     try {
       clientSession.createConsumer(queueName);
       Assert.fail("should throw exception");
     } catch (HornetQException e) {
       Assert.assertEquals(e.getCode(), HornetQException.QUEUE_DOES_NOT_EXIST);
     }
     clientSession.close();
   } finally {
     service.stop();
   }
 }
 public void testCreateConsumerWithInvalidFilter() throws Exception {
   HornetQServer service = createServer(false);
   try {
     service.start();
     ClientSessionFactory cf = createInVMFactory();
     cf.setProducerMaxRate(99);
     cf.setBlockOnNonDurableSend(true);
     cf.setBlockOnNonDurableSend(true);
     ClientSessionInternal clientSession =
         (ClientSessionInternal) cf.createSession(false, true, true);
     clientSession.createQueue(queueName, queueName, false);
     try {
       clientSession.createConsumer(queueName, "foobar");
       Assert.fail("should throw exception");
     } catch (HornetQException e) {
       Assert.assertEquals(e.getCode(), HornetQException.INVALID_FILTER_EXPRESSION);
     }
     clientSession.close();
   } finally {
     service.stop();
   }
 }
  public void open(final String fileName, final int maxIO) throws HornetQException {
    writeLock.lock();

    try {
      if (opened) {
        throw new IllegalStateException("AsynchronousFile is already opened");
      }

      this.maxIO = maxIO;
      maxIOSemaphore = new Semaphore(this.maxIO);

      this.fileName = fileName;

      try {
        handler = AsynchronousFileImpl.init(fileName, this.maxIO, HornetQJournalLogger.LOGGER);
      } catch (HornetQException e) {
        HornetQException ex = null;
        if (e.getType() == HornetQExceptionType.NATIVE_ERROR_CANT_INITIALIZE_AIO) {
          ex =
              new HornetQException(
                  e.getType(),
                  "Can't initialize AIO. Currently AIO in use = "
                      + AsynchronousFileImpl.totalMaxIO.get()
                      + ", trying to allocate more "
                      + maxIO,
                  e);
        } else {
          ex = e;
        }
        throw ex;
      }
      opened = true;
      AsynchronousFileImpl.addMax(this.maxIO);
      nextWritingSequence.set(0);
      nextReadSequence = 0;
    } finally {
      writeLock.unlock();
    }
  }
    @Override
    public void connectionFailed(final HornetQException me, boolean failedOver) {
      if (me.getType() == HornetQExceptionType.DISCONNECTED) {
        // Backup has shut down - no need to log a stack trace
        HornetQServerLogger.LOGGER.replicationStopOnBackupShutdown();
      } else {
        HornetQServerLogger.LOGGER.replicationStopOnBackupFail(me);
      }

      try {
        stop();
      } catch (Exception e) {
        HornetQServerLogger.LOGGER.errorStoppingReplication(e);
      }
    }
Exemple #22
0
  /**
   * Due to networking issues or server issues the server may take longer to answer than expected..
   * the client may timeout the call throwing an exception and the client could eventually retry
   * another call, but the server could then answer a previous command issuing a
   * class-cast-exception. The expectedPacket will be used to filter out undesirable packets that
   * would belong to previous calls.
   */
  public Packet sendBlocking(final Packet packet, byte expectedPacket) throws HornetQException {
    String interceptionResult = invokeInterceptors(packet, interceptors, connection);

    if (interceptionResult != null) {
      // if we don't throw an exception here the client might not unblock
      throw HornetQClientMessageBundle.BUNDLE.interceptorRejectedPacket(interceptionResult);
    }

    if (closed) {
      throw HornetQClientMessageBundle.BUNDLE.connectionDestroyed();
    }

    if (connection.getBlockingCallTimeout() == -1) {
      throw new IllegalStateException(
          "Cannot do a blocking call timeout on a server side connection");
    }

    // Synchronized since can't be called concurrently by more than one thread and this can occur
    // E.g. blocking acknowledge() from inside a message handler at some time as other operation on
    // main thread
    synchronized (sendBlockingLock) {
      packet.setChannelID(id);

      final HornetQBuffer buffer = packet.encode(connection);

      lock.lock();

      try {
        if (failingOver) {
          try {
            if (connection.getBlockingCallFailoverTimeout() < 0) {
              while (failingOver) {
                failoverCondition.await();
              }
            } else {
              if (!failoverCondition.await(
                  connection.getBlockingCallFailoverTimeout(), TimeUnit.MILLISECONDS)) {
                HornetQClientLogger.LOGGER.debug("timed-out waiting for failover condition");
              }
            }
          } catch (InterruptedException e) {
            throw new HornetQInterruptedException(e);
          }
        }

        response = null;

        if (resendCache != null && packet.isRequiresConfirmations()) {
          resendCache.add(packet);
        }

        connection.getTransportConnection().write(buffer, false, false);

        long toWait = connection.getBlockingCallTimeout();

        long start = System.currentTimeMillis();

        while (!closed
            && (response == null
                || (response.getType() != PacketImpl.EXCEPTION
                    && response.getType() != expectedPacket))
            && toWait > 0) {
          try {
            sendCondition.await(toWait, TimeUnit.MILLISECONDS);
          } catch (InterruptedException e) {
            throw new HornetQInterruptedException(e);
          }

          if (response != null
              && response.getType() != PacketImpl.EXCEPTION
              && response.getType() != expectedPacket) {
            HornetQClientLogger.LOGGER.packetOutOfOrder(response, new Exception("trace"));
          }

          if (closed) {
            break;
          }

          final long now = System.currentTimeMillis();

          toWait -= now - start;

          start = now;
        }

        if (response == null) {
          throw HornetQClientMessageBundle.BUNDLE.timedOutSendingPacket(packet.getType());
        }

        if (response.getType() == PacketImpl.EXCEPTION) {
          final HornetQExceptionMessage mem = (HornetQExceptionMessage) response;

          HornetQException e = mem.getException();

          e.fillInStackTrace();

          throw e;
        }
      } finally {
        lock.unlock();
      }

      return response;
    }
  }
  public ClientSessionFactory createSessionFactory() throws HornetQException {
    assertOpen();

    initialise();

    if (initialConnectors == null && discoveryGroup != null) {
      // Wait for an initial broadcast to give us at least one node in the cluster
      long timeout =
          clusterConnection ? 0 : discoveryGroupConfiguration.getDiscoveryInitialWaitTimeout();
      boolean ok = discoveryGroup.waitForBroadcast(timeout);

      if (!ok) {
        throw HornetQMessageBundle.BUNDLE.connectionTimedOutInInitialBroadcast();
      }
    }

    ClientSessionFactoryInternal factory = null;

    synchronized (this) {
      boolean retry;
      int attempts = 0;
      do {
        retry = false;

        TransportConfiguration tc = selectConnector();
        if (tc == null) {
          throw HornetQMessageBundle.BUNDLE.noTCForSessionFactory();
        }

        // try each factory in the list until we find one which works

        try {
          factory =
              new ClientSessionFactoryImpl(
                  this,
                  tc,
                  callTimeout,
                  callFailoverTimeout,
                  clientFailureCheckPeriod,
                  connectionTTL,
                  retryInterval,
                  retryIntervalMultiplier,
                  maxRetryInterval,
                  reconnectAttempts,
                  threadPool,
                  scheduledThreadPool,
                  interceptors);
          try {
            addToConnecting(factory);
            factory.connect(initialConnectAttempts, failoverOnInitialConnection);
          } finally {
            removeFromConnecting(factory);
          }
        } catch (HornetQException e) {
          factory.close();
          factory = null;
          if (e.getType() == HornetQExceptionType.NOT_CONNECTED) {
            attempts++;

            if (topologyArray != null && attempts == topologyArray.length) {
              throw HornetQMessageBundle.BUNDLE.cannotConnectToServers();
            }
            if (topologyArray == null
                && initialConnectors != null
                && attempts == initialConnectors.length) {
              throw HornetQMessageBundle.BUNDLE.cannotConnectToServers();
            }
            retry = true;
          } else {
            throw e;
          }
        }
      } while (retry);

      if (ha || clusterConnection) {
        final long timeout = System.currentTimeMillis() + 30000;
        while (!isClosed() && !receivedTopology && timeout > System.currentTimeMillis()) {
          // Now wait for the topology

          try {
            wait(1000);
          } catch (InterruptedException ignore) {
          }
        }

        if (System.currentTimeMillis() > timeout && !receivedTopology) {
          throw HornetQMessageBundle.BUNDLE.connectionTimedOutOnReceiveTopology(discoveryGroup);
        }
      }

      addFactory(factory);

      return factory;
    }
  }