Ejemplo n.º 1
0
 /**
  * Calls {@link #getMockedConnection(Configuration)} and then mocks a few more of the popular
  * {@link ClusterConnection} methods so they do 'normal' operation (see return doc below for
  * list). Be sure to shutdown the connection when done by calling {@link Connection#close()} else
  * it will stick around; this is probably not what you want.
  *
  * @param conf Configuration to use
  * @param admin An AdminProtocol; can be null but is usually itself a mock.
  * @param client A ClientProtocol; can be null but is usually itself a mock.
  * @param sn ServerName to include in the region location returned by this <code>connection</code>
  * @param hri HRegionInfo to include in the location returned when getRegionLocator is called on
  *     the mocked connection
  * @return Mock up a connection that returns a {@link Configuration} when {@link
  *     ClusterConnection#getConfiguration()} is called, a 'location' when {@link
  *     ClusterConnection#getRegionLocation(org.apache.hadoop.hbase.TableName, byte[], boolean)} is
  *     called, and that returns the passed {@link AdminProtos.AdminService.BlockingInterface}
  *     instance when {@link ClusterConnection#getAdmin(ServerName)} is called, returns the passed
  *     {@link ClientProtos.ClientService.BlockingInterface} instance when {@link
  *     ClusterConnection#getClient(ServerName)} is called (Be sure to call {@link
  *     Connection#close()} when done with this mocked Connection.
  * @throws IOException
  */
 public static ClusterConnection getMockedConnectionAndDecorate(
     final Configuration conf,
     final AdminProtos.AdminService.BlockingInterface admin,
     final ClientProtos.ClientService.BlockingInterface client,
     final ServerName sn,
     final HRegionInfo hri)
     throws IOException {
   ConnectionImplementation c = Mockito.mock(ConnectionImplementation.class);
   Mockito.when(c.getConfiguration()).thenReturn(conf);
   Mockito.doNothing().when(c).close();
   // Make it so we return a particular location when asked.
   final HRegionLocation loc = new HRegionLocation(hri, sn);
   Mockito.when(
           c.getRegionLocation(
               (TableName) Mockito.any(), (byte[]) Mockito.any(), Mockito.anyBoolean()))
       .thenReturn(loc);
   Mockito.when(c.locateRegion((TableName) Mockito.any(), (byte[]) Mockito.any())).thenReturn(loc);
   Mockito.when(
           c.locateRegion(
               (TableName) Mockito.any(),
               (byte[]) Mockito.any(),
               Mockito.anyBoolean(),
               Mockito.anyBoolean(),
               Mockito.anyInt()))
       .thenReturn(new RegionLocations(loc));
   if (admin != null) {
     // If a call to getAdmin, return this implementation.
     Mockito.when(c.getAdmin(Mockito.any(ServerName.class))).thenReturn(admin);
   }
   if (client != null) {
     // If a call to getClient, return this client.
     Mockito.when(c.getClient(Mockito.any(ServerName.class))).thenReturn(client);
   }
   NonceGenerator ng = Mockito.mock(NonceGenerator.class);
   Mockito.when(c.getNonceGenerator()).thenReturn(ng);
   Mockito.when(c.getAsyncProcess())
       .thenReturn(
           new AsyncProcess(
               c,
               conf,
               null,
               RpcRetryingCallerFactory.instantiate(conf),
               false,
               RpcControllerFactory.instantiate(conf),
               conf.getInt(HConstants.HBASE_RPC_TIMEOUT_KEY, HConstants.DEFAULT_HBASE_RPC_TIMEOUT),
               conf.getInt(
                   HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
                   HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT)));
   Mockito.when(c.getNewRpcRetryingCallerFactory(conf))
       .thenReturn(
           RpcRetryingCallerFactory.instantiate(
               conf, RetryingCallerInterceptorFactory.NO_OP_INTERCEPTOR, null));
   Mockito.when(c.getRpcControllerFactory()).thenReturn(Mockito.mock(RpcControllerFactory.class));
   Table t = Mockito.mock(Table.class);
   Mockito.when(c.getTable((TableName) Mockito.any())).thenReturn(t);
   ResultScanner rs = Mockito.mock(ResultScanner.class);
   Mockito.when(t.getScanner((Scan) Mockito.any())).thenReturn(rs);
   return c;
 }
  @Test
  public void testReplyToOneDeepCustomCorrelationKey() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    final RabbitTemplate template =
        new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory));
    template.setCorrelationKey(CORRELATION_HEADER);
    Queue replyQueue = new Queue("new.replyTo");
    template.setReplyQueue(replyQueue);

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setReplyTo("replyTo1");
    messageProperties.setCorrelationId("saveThis".getBytes());
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    final AtomicReference<String> replyTo = new AtomicReference<String>();
    final AtomicReference<String> correlationId = new AtomicReference<String>();
    doAnswer(
            new Answer<Object>() {
              public Object answer(InvocationOnMock invocation) throws Throwable {
                BasicProperties basicProps = (BasicProperties) invocation.getArguments()[4];
                replyTo.set(basicProps.getReplyTo());
                correlationId.set((String) basicProps.getHeaders().get(CORRELATION_HEADER));

                MessageProperties springProps =
                    new DefaultMessagePropertiesConverter()
                        .toMessageProperties(basicProps, null, "UTF-8");
                Message replyMessage = new Message("!dlrow olleH".getBytes(), springProps);
                template.onMessage(replyMessage);
                return null;
              }
            })
        .when(mockChannel)
        .basicPublish(
            Mockito.any(String.class),
            Mockito.any(String.class),
            Mockito.anyBoolean(),
            Mockito.anyBoolean(),
            Mockito.any(BasicProperties.class),
            Mockito.any(byte[].class));
    Message reply = template.sendAndReceive(message);
    assertNotNull(reply);

    assertNotNull(replyTo.get());
    assertEquals("new.replyTo", replyTo.get());
    assertNotNull(correlationId.get());
    assertEquals("replyTo1", reply.getMessageProperties().getReplyTo());
    assertTrue(!"saveThis".equals(correlationId.get()));
    assertEquals("replyTo1", reply.getMessageProperties().getReplyTo());
  }
  @SuppressWarnings("unchecked")
  @Test
  @Ignore
  public void testCanControlGatheredEntriesUsingRsm() throws Exception {

    NodeItem item1 = new NodeItemImpl(TEST_NODE_1, "node1:1", new Date(0), "<entry>item1</entry>");
    NodeItem item2 = new NodeItemImpl(TEST_NODE_2, "node2:1", new Date(10), "<entry>item2</entry>");
    NodeItem item3 = new NodeItemImpl(TEST_NODE_1, "node1:2", new Date(20), "<entry>item3</entry>");
    NodeItem item4 = new NodeItemImpl(TEST_NODE_1, "node1:3", new Date(30), "<entry>item4</entry>");

    ArrayList<NodeItem> results = new ArrayList<NodeItem>();
    results.add(item1);
    results.add(item2);
    results.add(item3);
    results.add(item4);

    Mockito.when(
            channelManager.getUserFeedItems(
                Mockito.any(JID.class),
                Mockito.any(Date.class),
                Mockito.anyInt(),
                Mockito.any(GlobalItemID.class),
                Mockito.anyBoolean()))
        .thenReturn(new ClosableIteratorImpl<NodeItem>(results.iterator()));
    Mockito.when(
            channelManager.getCountUserFeedItems(
                Mockito.any(JID.class), Mockito.any(Date.class), Mockito.anyBoolean()))
        .thenReturn(results.size());

    Element rsm = request.getElement().addElement("rsm");
    rsm.addNamespace("", PubSubElementProcessorAbstract.NS_RSM);
    rsm.addElement("max").addText("2");
    rsm.addElement("after").addText("node1:1");

    userItemsGet.process(element, jid, request, null);
    IQ response = (IQ) queue.poll();

    Assert.assertEquals(IQ.Type.result, response.getType());
    Element pubsub = response.getChildElement();
    Assert.assertEquals("pubsub", pubsub.getName());
    Assert.assertEquals(JabberPubsub.NAMESPACE_URI, pubsub.getNamespaceURI());

    List<Element> items = pubsub.elements("items");
    Assert.assertEquals(2, items.size());

    Assert.assertEquals(TEST_NODE_2, items.get(0).attributeValue("node"));
    Assert.assertEquals(TEST_NODE_1, items.get(1).attributeValue("node"));
    Assert.assertEquals(1, items.get(0).elements("item").size());
    Assert.assertEquals(1, items.get(1).elements("item").size());

    Element rsmResult = pubsub.element("set");
    Assert.assertEquals("2", rsmResult.element("count").getText());
    Assert.assertEquals("node2:1", rsmResult.element("first").getText());
    Assert.assertEquals("node1:2", rsmResult.element("last").getText());
  }
  @Test
  public void testInactiveControlRetriedOnceAndSucceeds() throws InterruptedException {
    final WebTarget QUALIFY_TARGET = Mockito.mock(WebTarget.class);
    final WebTarget FOLLOW_TARGET = Mockito.mock(WebTarget.class);
    final Invocation.Builder QUALIFY_BUILDER = Mockito.mock(Invocation.Builder.class);
    final AsyncInvoker QUALIFY_ASYNC = Mockito.mock(AsyncInvoker.class);
    final Invocation.Builder FOLLOW_BUILDER = Mockito.mock(Invocation.Builder.class);
    final AsyncInvoker FOLLOW_ASYNC = Mockito.mock(AsyncInvoker.class);

    Mockito.when(QUALIFY_TARGET.request()).thenReturn(QUALIFY_BUILDER);
    Mockito.when(QUALIFY_BUILDER.async()).thenReturn(QUALIFY_ASYNC);
    Mockito.when(FOLLOW_TARGET.request()).thenReturn(FOLLOW_BUILDER);
    Mockito.when(FOLLOW_BUILDER.async()).thenReturn(FOLLOW_ASYNC);

    final ChannelMonitor MONITOR =
        new RetryingControlChannelMonitor(config(), QUALIFY_TARGET, FOLLOW_TARGET);
    final Future CAPTURE_FUTURE = Mockito.mock(Future.class);
    final DataUnitCounter COUNTER = Mockito.mock(DataUnitCounter.class);

    Mockito.when(COUNTER.getDataUnitCount()).thenReturn(0);

    final ControlChannelId id = new ControlChannelId(10, 20, 30, 40);
    final Identifiable capture = new FollowRequest(10d, 20d, 0, 1337d, id);

    assert MONITOR.monitor(capture, CAPTURE_FUTURE, COUNTER);
    assert MONITOR.contains(id);
    Mockito.verify(CAPTURE_FUTURE, Mockito.never()).cancel(Mockito.anyBoolean());

    Thread.sleep(1100);

    Mockito.verify(CAPTURE_FUTURE, Mockito.times(1)).cancel(Mockito.anyBoolean());
    assert MONITOR.contains(id);

    ArgumentCaptor<InvocationCallback> QUALIFY_CALLBACK =
        ArgumentCaptor.forClass(InvocationCallback.class);
    Mockito.verify(QUALIFY_ASYNC).post(Mockito.any(Entity.class), QUALIFY_CALLBACK.capture());

    ControlChannelQualities QUALITIES = Mockito.mock(ControlChannelQualities.class);
    Mockito.when(QUALITIES.getWacn()).thenReturn(id.getWacn());
    Mockito.when(QUALITIES.getSystemId()).thenReturn(id.getSystemId());
    Mockito.when(QUALITIES.getRfSubsystemId()).thenReturn(id.getRfSubsystemId());
    Mockito.when(QUALITIES.getSiteId()).thenReturn(id.getSiteId());

    QUALIFY_CALLBACK.getValue().completed(QUALITIES);

    assert !MONITOR.contains(id);
    Mockito.verify(FOLLOW_ASYNC, Mockito.times(1))
        .post(Mockito.any(Entity.class), Mockito.any(InvocationCallback.class));
  }
 @Test(expected = IOException.class)
 public void testPrepareConfigFilesThrowsExceptionWhenUnzipFailed() throws IOException {
   doThrow(IOException.class)
       .when(archiverService)
       .unzip(Mockito.<InputStream>any(), Mockito.anyBoolean());
   yarnConfigFilesProvider.prepareConfigFiles();
 }
  @Before
  public void before() throws KettleException {
    MockitoAnnotations.initMocks(this);

    Mockito.when(parentJob.getLogLevel()).thenReturn(LogLevel.BASIC);
    entry.setParentJob(parentJob);
    entry.setSaveMessage(true);

    Mockito.when(message.getMessageNumber()).thenReturn(1);
    Mockito.when(mailConn.getMessage()).thenReturn(message);

    Mockito.doNothing().when(mailConn).openFolder(Mockito.anyBoolean());
    Mockito.doNothing().when(mailConn).openFolder(Mockito.anyString(), Mockito.anyBoolean());

    Mockito.when(mailConn.getMessagesCount()).thenReturn(1);
  }
  @Test
  public void testCancel() {
    final WebTarget QUALIFY = Mockito.mock(WebTarget.class);
    final WebTarget FOLLOW = Mockito.mock(WebTarget.class);
    final ChannelMonitor MONITOR = new RetryingControlChannelMonitor(config(), QUALIFY, FOLLOW);
    final Future FUTURE = Mockito.mock(Future.class);
    final DataUnitCounter COUNTER = Mockito.mock(DataUnitCounter.class);

    Mockito.when(COUNTER.getDataUnitCount()).thenReturn(1337);

    final GroupChannelId id = new GroupChannelId(10, 20, 30, 40, 50, 60d);
    final Identifiable capture = new GroupCaptureRequest(10d, 20d, 0, 1337d, id);

    assert MONITOR.monitor(capture, FUTURE, COUNTER);
    assert MONITOR.contains(id);
    Mockito.verify(FUTURE, Mockito.never()).cancel(Mockito.anyBoolean());

    MONITOR.cancel(id);

    Mockito.verify(FUTURE, Mockito.times(1)).cancel(Mockito.anyBoolean());
    assert !MONITOR.contains(id);
  }
  @Test
  public void whenRequestingParentOnlyCorrectFlagIsSetOnDatabaseRequest() throws Exception {
    Element rsm =
        new BaseElement(new QName("set", new Namespace("", "http://jabber.org/protocol/rsm")));

    element.addAttribute("node", "/user/[email protected]/posts");

    IQ request = this.request.createCopy();
    request.getChildElement().element("user-items").addAttribute("parent-only", "true");

    Mockito.when(channelManager.nodeExists(anyString())).thenReturn(true);

    Mockito.when(channelManager.getNodeMembership(node, jid))
        .thenReturn(
            new NodeMembershipImpl(node, jid, Subscriptions.subscribed, Affiliations.member, null));

    Mockito.when(
            channelManager.getUserFeedItems(
                Mockito.any(JID.class),
                Mockito.any(Date.class),
                Mockito.anyInt(),
                Mockito.any(GlobalItemID.class),
                Mockito.anyBoolean()))
        .thenReturn(new ClosableIteratorImpl<NodeItem>(new ArrayList<NodeItem>().iterator()));
    Mockito.when(
            channelManager.getCountUserFeedItems(
                Mockito.any(JID.class), Mockito.any(Date.class), Mockito.anyBoolean()))
        .thenReturn(0);

    userItemsGet.process(element, jid, request, rsm);

    Mockito.verify(channelManager, Mockito.times(1))
        .getUserFeedItems(
            Mockito.any(JID.class),
            Mockito.any(Date.class),
            Mockito.anyInt(),
            Mockito.any(GlobalItemID.class),
            Mockito.eq(true));
  }
  @Before
  public void setUp() {
    MockApplication application = new MyMockApplicationEx(parent);
    ActionManagerEx manager = Mockito.mock(ActionManagerEx.class);
    ActionToolbar actionToolbar = Mockito.mock(ActionToolbar.class);
    Mockito.when(actionToolbar.getComponent()).thenReturn(new JComponent() {});
    Mockito.when(
            manager.createActionToolbar(
                Mockito.anyString(), Mockito.any(ActionGroup.class), Mockito.anyBoolean()))
        .thenReturn(actionToolbar);
    Mockito.when(
            manager.createActionToolbar(
                Mockito.anyString(),
                Mockito.any(ActionGroup.class),
                Mockito.anyBoolean(),
                Mockito.anyBoolean()))
        .thenReturn(actionToolbar);
    application.addComponent(ActionManager.class, manager);
    ApplicationManager.setApplication(application, parent);

    XDebugSession session = Mockito.mock(XDebugSession.class);
    Mockito.when(handler.getProcess()).thenReturn(mockProcess);
    Mockito.when(mockProcess.getXDebugSession()).thenReturn(session);
  }
Ejemplo n.º 10
0
 /**
  * Test get of root region fails properly if nothing to connect to.
  *
  * @throws IOException
  * @throws InterruptedException
  * @throws KeeperException
  */
 @Test
 public void testVerifyRootRegionLocationFails()
     throws IOException, InterruptedException, KeeperException {
   HConnection connection = Mockito.mock(HConnection.class);
   ConnectException connectException = new ConnectException("Connection refused");
   final HRegionInterface implementation = Mockito.mock(HRegionInterface.class);
   Mockito.when(implementation.getRegionInfo((byte[]) Mockito.any())).thenThrow(connectException);
   Mockito.when(
           connection.getHRegionConnection(
               Mockito.anyString(), Mockito.anyInt(), Mockito.anyBoolean()))
       .thenReturn(implementation);
   final CatalogTracker ct = constructAndStartCatalogTracker(connection);
   RootLocationEditor.setRootLocation(
       this.watcher, new ServerName("example.com", 1234, System.currentTimeMillis()));
   Assert.assertFalse(ct.verifyRootRegionLocation(100));
 }
  @Test
  public void testDatasourceProvider() throws Exception {

    mondrianCatalogHelper = mock(MondrianCatalogHelper.class);

    // steelwheels mondrian catalog
    MondrianSchema steelWheelsSchema =
        new MondrianSchema(STEEL_WHEELS, Arrays.asList(new MondrianCube[] {mockCube}));
    MondrianCatalog steelWheelsCatalog =
        new MondrianCatalog(
            STEEL_WHEELS, MONDRIAN_DS_PROVIDER, STEEL_WHEELS + ".mondrian.xml", steelWheelsSchema);

    // sampledata mondrian catalog
    MondrianSchema sampleDataSchema =
        new MondrianSchema(SAMPLE_DATA, Arrays.asList(new MondrianCube[] {mockCube}));
    MondrianCatalog sampleDataCatalog =
        new MondrianCatalog(
            SAMPLE_DATA, MONDRIAN_DS_PROVIDER, SAMPLE_DATA + ".mondrian.xml", sampleDataSchema);

    // add catalogs to mondrianCatalogHelper
    mondrianCatalogHelper.addCatalog(steelWheelsCatalog, false, standaloneSession);
    mondrianCatalogHelper.addCatalog(sampleDataCatalog, false, standaloneSession);

    List<MondrianCatalog> returnList = new ArrayList<MondrianCatalog>();
    returnList.add(sampleDataCatalog);
    returnList.add(steelWheelsCatalog);

    // mock mondrianCatalogHelper.listCatalogs return
    doReturn(returnList)
        .when(mondrianCatalogHelper)
        .listCatalogs(Mockito.any(IPentahoSession.class), Mockito.anyBoolean());

    // create AnalysisDatasourceProvider
    IDatasourceProvider analysisDatasourceProvider =
        new AnalysisDatasourceProvider(mondrianCatalogHelper);
    List<IDatasource> datasources = analysisDatasourceProvider.getDatasources();

    assertEquals(2, datasources.size());

    assertEquals(SAMPLE_DATA, datasources.get(0).getName());
    assertEquals(ANALYSIS_TYPE, datasources.get(0).getType().getId());

    assertEquals(STEEL_WHEELS, datasources.get(1).getName());
    assertEquals(ANALYSIS_TYPE, datasources.get(1).getType().getId());
  }
Ejemplo n.º 12
0
 @SuppressWarnings("unchecked")
 @Test
 public void testTransactionStatementsAsynch() throws Exception {
   ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
   Mockito.stub(conn.submitSetAutoCommitTrue(Mockito.anyBoolean()))
       .toReturn((ResultsFuture) ResultsFuture.NULL_FUTURE);
   Properties p = new Properties();
   Mockito.stub(conn.getExecutionProperties()).toReturn(p);
   StatementImpl statement =
       new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
   statement.submitExecute("start transaction", null); // $NON-NLS-1$
   Mockito.verify(conn).setAutoCommit(false);
   statement.submitExecute("commit", null); // $NON-NLS-1$
   Mockito.verify(conn).submitSetAutoCommitTrue(true);
   statement.submitExecute("start transaction", null); // $NON-NLS-1$
   statement.submitExecute("rollback", null); // $NON-NLS-1$
   Mockito.verify(conn).submitSetAutoCommitTrue(false);
 }
Ejemplo n.º 13
0
 /**
  * @param implementation An {@link HRegionInterface} instance; you'll likely want to pass a mocked
  *     HRS; can be null.
  * @return Mock up a connection that returns a {@link org.apache.hadoop.conf.Configuration} when
  *     {@link HConnection#getConfiguration()} is called, a 'location' when {@link
  *     HConnection#getRegionLocation(byte[], byte[], boolean)} is called, and that returns the
  *     passed {@link HRegionInterface} instance when {@link
  *     HConnection#getHRegionConnection(String, int)} is called (Be sure call {@link
  *     HConnectionManager#deleteConnection(org.apache.hadoop.conf.Configuration)} when done with
  *     this mocked Connection.
  * @throws IOException
  */
 private HConnection mockConnection(final HRegionInterface implementation) throws IOException {
   HConnection connection = HConnectionTestingUtility.getMockedConnection(UTIL.getConfiguration());
   Mockito.doNothing().when(connection).close();
   // Make it so we return any old location when asked.
   final HRegionLocation anyLocation =
       new HRegionLocation(HRegionInfo.FIRST_META_REGIONINFO, SN.getHostname(), SN.getPort());
   Mockito.when(
           connection.getRegionLocation(
               (byte[]) Mockito.any(), (byte[]) Mockito.any(), Mockito.anyBoolean()))
       .thenReturn(anyLocation);
   Mockito.when(connection.locateRegion((byte[]) Mockito.any(), (byte[]) Mockito.any()))
       .thenReturn(anyLocation);
   if (implementation != null) {
     // If a call to getHRegionConnection, return this implementation.
     Mockito.when(connection.getHRegionConnection(Mockito.anyString(), Mockito.anyInt()))
         .thenReturn(implementation);
   }
   return connection;
 }
  @SuppressWarnings("unchecked")
  @Test
  public void testOutgoingStanzaFormattedAsExpected() throws Exception {

    NodeItem item1 = new NodeItemImpl(TEST_NODE_1, "1", new Date(), "<entry>item1</entry>");
    NodeItem item2 = new NodeItemImpl(TEST_NODE_2, "1", new Date(), "<entry>item2</entry>");
    NodeItem item3 = new NodeItemImpl(TEST_NODE_1, "2", new Date(), "<entry>item3</entry>");
    NodeItem item4 = new NodeItemImpl(TEST_NODE_1, "3", new Date(), "<entry>item4</entry>");

    ArrayList<NodeItem> results = new ArrayList<NodeItem>();
    results.add(item1);
    results.add(item2);
    results.add(item3);
    results.add(item4);

    Mockito.when(
            channelManager.getUserFeedItems(
                Mockito.any(JID.class),
                Mockito.any(Date.class),
                Mockito.anyInt(),
                Mockito.any(GlobalItemID.class),
                Mockito.anyBoolean()))
        .thenReturn(new ClosableIteratorImpl<NodeItem>(results.iterator()));

    userItemsGet.process(element, jid, request, null);
    IQ response = (IQ) queue.poll();

    Assert.assertEquals(IQ.Type.result, response.getType());
    Element pubsub = response.getChildElement();
    Assert.assertEquals("pubsub", pubsub.getName());
    Assert.assertEquals(JabberPubsub.NAMESPACE_URI, pubsub.getNamespaceURI());

    List<Element> items = pubsub.elements("items");
    Assert.assertEquals(3, items.size());

    Assert.assertEquals(TEST_NODE_1, items.get(0).attributeValue("node"));
    Assert.assertEquals(TEST_NODE_2, items.get(1).attributeValue("node"));
    Assert.assertEquals(TEST_NODE_1, items.get(2).attributeValue("node"));

    Assert.assertEquals(1, items.get(0).elements("item").size());
    Assert.assertEquals(2, items.get(2).elements("item").size());
  }
  @Test
  public void testNodeStoreExceptionGeneratesAnErrorStanza() throws Exception {

    Mockito.when(
            channelManager.getUserFeedItems(
                Mockito.any(JID.class),
                Mockito.any(Date.class),
                Mockito.anyInt(),
                Mockito.any(GlobalItemID.class),
                Mockito.anyBoolean()))
        .thenThrow(new NodeStoreException());

    userItemsGet.process(element, jid, request, null);
    Packet response = queue.poll();

    PacketError error = response.getError();
    Assert.assertNotNull(error);
    Assert.assertEquals(PacketError.Type.wait, error.getType());
    Assert.assertEquals(PacketError.Condition.internal_server_error, error.getCondition());
  }
  @Test
  public void testNoUserItemsReturnsEmptyStanza() throws Exception {

    Mockito.when(
            channelManager.getUserFeedItems(
                Mockito.any(JID.class),
                Mockito.any(Date.class),
                Mockito.anyInt(),
                Mockito.any(GlobalItemID.class),
                Mockito.anyBoolean()))
        .thenReturn(new ClosableIteratorImpl<NodeItem>(new ArrayList<NodeItem>().iterator()));

    userItemsGet.process(element, jid, request, null);
    IQ response = (IQ) queue.poll();

    Assert.assertEquals(IQ.Type.result, response.getType());
    Element pubsub = response.getChildElement();
    Assert.assertEquals("pubsub", pubsub.getName());
    Assert.assertEquals(JabberPubsub.NAMESPACE_URI, pubsub.getNamespaceURI());
  }
Ejemplo n.º 17
0
 /**
  * Calls {@link #getMockedConnection(Configuration)} and then mocks a few more of the popular
  * {@link HConnection} methods so they do 'normal' operation (see return doc below for list). Be
  * sure to shutdown the connection when done by calling {@link
  * HConnectionManager#deleteConnection(Configuration, boolean)} else it will stick around; this is
  * probably not what you want.
  *
  * @param implementation An {@link HRegionInterface} instance; you'll likely want to pass a mocked
  *     HRS; can be null.
  * @param conf Configuration to use
  * @param implementation An HRegionInterface; can be null but is usually itself a mock.
  * @param sn ServerName to include in the region location returned by this <code>implementation
  *     </code>
  * @param hri HRegionInfo to include in the location returned when getRegionLocation is called on
  *     the mocked connection
  * @return Mock up a connection that returns a {@link Configuration} when {@link
  *     HConnection#getConfiguration()} is called, a 'location' when {@link
  *     HConnection#getRegionLocation(byte[], byte[], boolean)} is called, and that returns the
  *     passed {@link HRegionInterface} instance when {@link
  *     HConnection#getHRegionConnection(String, int)} is called (Be sure call {@link
  *     HConnectionManager#deleteConnection(org.apache.hadoop.conf.Configuration, boolean)} when
  *     done with this mocked Connection.
  * @throws IOException
  */
 public static HConnection getMockedConnectionAndDecorate(
     final Configuration conf,
     final HRegionInterface implementation,
     final ServerName sn,
     final HRegionInfo hri)
     throws IOException {
   HConnection c = HConnectionTestingUtility.getMockedConnection(conf);
   Mockito.doNothing().when(c).close();
   // Make it so we return a particular location when asked.
   final HRegionLocation loc = new HRegionLocation(hri, sn.getHostname(), sn.getPort());
   Mockito.when(
           c.getRegionLocation(
               (byte[]) Mockito.any(), (byte[]) Mockito.any(), Mockito.anyBoolean()))
       .thenReturn(loc);
   Mockito.when(c.locateRegion((byte[]) Mockito.any(), (byte[]) Mockito.any())).thenReturn(loc);
   if (implementation != null) {
     // If a call to getHRegionConnection, return this implementation.
     Mockito.when(c.getHRegionConnection(Mockito.anyString(), Mockito.anyInt()))
         .thenReturn(implementation);
   }
   return c;
 }
  @Test
  public void testUnparsableItemEntriesAreSimplyIgnored() throws Exception {

    NodeItem item1 = new NodeItemImpl(TEST_NODE_1, "1", new Date(), "<entry>item1</entry>");
    NodeItem item2 = new NodeItemImpl(TEST_NODE_1, "2", new Date(), "<entry>item2");

    ArrayList<NodeItem> results = new ArrayList<NodeItem>();
    results.add(item1);
    results.add(item2);

    Mockito.when(
            channelManager.getUserFeedItems(
                Mockito.any(JID.class),
                Mockito.any(Date.class),
                Mockito.anyInt(),
                Mockito.any(GlobalItemID.class),
                Mockito.anyBoolean()))
        .thenReturn(new ClosableIteratorImpl<NodeItem>(results.iterator()));

    userItemsGet.process(element, jid, request, null);
    IQ response = (IQ) queue.poll();
    Assert.assertEquals(1, response.getChildElement().element("items").elements("item").size());
  }
  @Test
  public void deliveryAssignmentEmailNotificationTest_Original_Basic() throws MitchellException {
    try {
      APDDeliveryContextDocument aPDDeliveryContextDocument =
          APDDeliveryContextDocument.Factory.parse(
              new File("src/test/resources/APDDeliveryContextDocument.xml"));
      Mockito.doNothing()
          .when(assignmentEmailDeliveryHandler)
          .deliverIAEmail(
              (APDDeliveryContextDocument) Mockito.anyObject(),
              Mockito.anyBoolean(),
              Mockito.anyString());
      asgEmailDelService.deliveryAssignmentEmailNotification(
          aPDDeliveryContextDocument, new ArrayList<String>(), "IA_BASIC_EMAIL_TYPE");
      Mockito.when(cultureDAO.getCultureByCompany(Mockito.anyString())).thenReturn(null);
      Mockito.verify(assignmentEmailDeliveryHandler)
          .deliverIAEmail(aPDDeliveryContextDocument, true, "en-US");

    } catch (XmlException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * Test that MetaReader will ride over server throwing "Server not running" IOEs.
   *
   * @see https://issues.apache.org/jira/browse/HBASE-3446
   * @throws IOException
   * @throws InterruptedException
   */
  @Test
  public void testRideOverServerNotRunning() throws IOException, InterruptedException {
    // Need a zk watcher.
    ZooKeeperWatcher zkw =
        new ZooKeeperWatcher(
            UTIL.getConfiguration(), this.getClass().getSimpleName(), ABORTABLE, true);
    // This is a servername we use in a few places below.
    ServerName sn = new ServerName("example.com", 1234, System.currentTimeMillis());

    HConnection connection = null;
    CatalogTracker ct = null;
    try {
      // Mock an HRegionInterface. Our mock implementation will fail a few
      // times when we go to open a scanner.
      final HRegionInterface implementation = Mockito.mock(HRegionInterface.class);
      // When openScanner called throw IOE 'Server not running' a few times
      // before we return a scanner id.  Whats WEIRD is that these
      // exceptions do not show in the log because they are caught and only
      // printed if we FAIL.  We eventually succeed after retry so these don't
      // show.  We will know if they happened or not because we will ask
      // mockito at the end of this test to verify that openscanner was indeed
      // called the wanted number of times.
      final long scannerid = 123L;
      Mockito.when(implementation.openScanner((byte[]) Mockito.any(), (Scan) Mockito.any()))
          .thenThrow(new IOException("Server not running (1 of 3)"))
          .thenThrow(new IOException("Server not running (2 of 3)"))
          .thenThrow(new IOException("Server not running (3 of 3)"))
          .thenReturn(scannerid);
      // Make it so a verifiable answer comes back when next is called.  Return
      // the verifiable answer and then a null so we stop scanning.  Our
      // verifiable answer is something that looks like a row in META with
      // a server and startcode that is that of the above defined servername.
      List<KeyValue> kvs = new ArrayList<KeyValue>();
      final byte[] rowToVerify = Bytes.toBytes("rowToVerify");
      kvs.add(
          new KeyValue(
              rowToVerify,
              HConstants.CATALOG_FAMILY,
              HConstants.REGIONINFO_QUALIFIER,
              Writables.getBytes(HRegionInfo.FIRST_META_REGIONINFO)));
      kvs.add(
          new KeyValue(
              rowToVerify,
              HConstants.CATALOG_FAMILY,
              HConstants.SERVER_QUALIFIER,
              Bytes.toBytes(sn.getHostAndPort())));
      kvs.add(
          new KeyValue(
              rowToVerify,
              HConstants.CATALOG_FAMILY,
              HConstants.STARTCODE_QUALIFIER,
              Bytes.toBytes(sn.getStartcode())));
      final Result[] result = new Result[] {new Result(kvs)};
      Mockito.when(implementation.next(Mockito.anyLong(), Mockito.anyInt()))
          .thenReturn(result)
          .thenReturn(null);

      // Associate a spied-upon HConnection with UTIL.getConfiguration.  Need
      // to shove this in here first so it gets picked up all over; e.g. by
      // HTable.
      connection = HConnectionTestingUtility.getSpiedConnection(UTIL.getConfiguration());
      // Fix the location lookup so it 'works' though no network.  First
      // make an 'any location' object.
      final HRegionLocation anyLocation =
          new HRegionLocation(HRegionInfo.FIRST_META_REGIONINFO, sn.getHostname(), sn.getPort());
      // Return the any location object when locateRegion is called in HTable
      // constructor and when its called by ServerCallable (it uses getRegionLocation).
      // The ugly format below comes of 'Important gotcha on spying real objects!' from
      // http://mockito.googlecode.com/svn/branches/1.6/javadoc/org/mockito/Mockito.html
      Mockito.doReturn(anyLocation)
          .when(connection)
          .locateRegion((byte[]) Mockito.any(), (byte[]) Mockito.any());
      Mockito.doReturn(anyLocation)
          .when(connection)
          .getRegionLocation((byte[]) Mockito.any(), (byte[]) Mockito.any(), Mockito.anyBoolean());

      // Now shove our HRI implementation into the spied-upon connection.
      Mockito.doReturn(implementation)
          .when(connection)
          .getHRegionConnection(Mockito.anyString(), Mockito.anyInt());

      // Now start up the catalogtracker with our doctored Connection.
      ct = new CatalogTracker(zkw, null, connection, ABORTABLE, 0);
      ct.start();
      // Scan meta for user tables and verify we got back expected answer.
      NavigableMap<HRegionInfo, Result> hris = MetaReader.getServerUserRegions(ct, sn);
      assertTrue(hris.size() == 1);
      assertTrue(hris.firstEntry().getKey().equals(HRegionInfo.FIRST_META_REGIONINFO));
      assertTrue(Bytes.equals(rowToVerify, hris.firstEntry().getValue().getRow()));
      // Finally verify that openscanner was called four times -- three times
      // with exception and then on 4th attempt we succeed.
      Mockito.verify(implementation, Mockito.times(4))
          .openScanner((byte[]) Mockito.any(), (Scan) Mockito.any());
    } finally {
      if (ct != null) ct.stop();
      HConnectionManager.deleteConnection(UTIL.getConfiguration(), true);
      zkw.close();
    }
  }
  /** Verifies that an up-stack RabbitTemplate uses the listener's channel (MessageListener). */
  @SuppressWarnings("unchecked")
  @Test
  public void testMessageListener() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    final Channel onlyChannel = mock(Channel.class);
    when(onlyChannel.isOpen()).thenReturn(true);

    final CachingConnectionFactory cachingConnectionFactory =
        new CachingConnectionFactory(mockConnectionFactory);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);

    final AtomicReference<Exception> tooManyChannels = new AtomicReference<Exception>();

    doAnswer(
            new Answer<Channel>() {
              boolean done;

              @Override
              public Channel answer(InvocationOnMock invocation) throws Throwable {
                if (!done) {
                  done = true;
                  return onlyChannel;
                }
                tooManyChannels.set(new Exception("More than one channel requested"));
                Channel channel = mock(Channel.class);
                when(channel.isOpen()).thenReturn(true);
                return channel;
              }
            })
        .when(mockConnection)
        .createChannel();

    final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>();

    doAnswer(
            new Answer<String>() {

              @Override
              public String answer(InvocationOnMock invocation) throws Throwable {
                consumer.set((Consumer) invocation.getArguments()[6]);
                return null;
              }
            })
        .when(onlyChannel)
        .basicConsume(
            anyString(),
            anyBoolean(),
            anyString(),
            anyBoolean(),
            anyBoolean(),
            anyMap(),
            any(Consumer.class));

    final CountDownLatch commitLatch = new CountDownLatch(1);
    doAnswer(
            new Answer<String>() {

              @Override
              public String answer(InvocationOnMock invocation) throws Throwable {
                commitLatch.countDown();
                return null;
              }
            })
        .when(onlyChannel)
        .txCommit();

    final CountDownLatch latch = new CountDownLatch(1);
    SimpleMessageListenerContainer container =
        new SimpleMessageListenerContainer(cachingConnectionFactory);
    container.setMessageListener(
        new MessageListener() {
          @Override
          public void onMessage(Message message) {
            RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
            rabbitTemplate.setChannelTransacted(true);
            // should use same channel as container
            rabbitTemplate.convertAndSend("foo", "bar", "baz");
            latch.countDown();
          }
        });
    container.setQueueNames("queue");
    container.setChannelTransacted(true);
    container.setShutdownTimeout(100);
    container.afterPropertiesSet();
    container.start();

    consumer
        .get()
        .handleDelivery(
            "qux", new Envelope(1, false, "foo", "bar"), new BasicProperties(), new byte[] {0});

    assertTrue(latch.await(10, TimeUnit.SECONDS));

    Exception e = tooManyChannels.get();
    if (e != null) {
      throw e;
    }

    verify(mockConnection, Mockito.times(1)).createChannel();
    assertTrue(commitLatch.await(10, TimeUnit.SECONDS));
    verify(onlyChannel).txCommit();
    verify(onlyChannel)
        .basicPublish(
            Mockito.anyString(),
            Mockito.anyString(),
            Mockito.anyBoolean(),
            Mockito.any(BasicProperties.class),
            Mockito.any(byte[].class));

    // verify close() was never called on the channel
    DirectFieldAccessor dfa = new DirectFieldAccessor(cachingConnectionFactory);
    List<?> channels = (List<?>) dfa.getPropertyValue("cachedChannelsTransactional");
    assertEquals(0, channels.size());

    container.stop();
  }
  /**
   * Verifies that the listener channel is not exposed when so configured and up-stack
   * RabbitTemplate uses the additional channel. created when exposeListenerChannel is false
   * (ChannelAwareMessageListener).
   */
  @SuppressWarnings("unchecked")
  @Test
  public void testChannelAwareMessageListenerDontExpose() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    final Channel firstChannel = mock(Channel.class);
    when(firstChannel.isOpen()).thenReturn(true);
    final Channel secondChannel = mock(Channel.class);
    when(secondChannel.isOpen()).thenReturn(true);

    final SingleConnectionFactory singleConnectionFactory =
        new SingleConnectionFactory(mockConnectionFactory);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);

    final AtomicReference<Exception> tooManyChannels = new AtomicReference<Exception>();

    doAnswer(
            new Answer<Channel>() {
              boolean done;

              @Override
              public Channel answer(InvocationOnMock invocation) throws Throwable {
                if (!done) {
                  done = true;
                  return firstChannel;
                }
                return secondChannel;
              }
            })
        .when(mockConnection)
        .createChannel();

    final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>();

    doAnswer(
            new Answer<String>() {

              @Override
              public String answer(InvocationOnMock invocation) throws Throwable {
                consumer.set((Consumer) invocation.getArguments()[6]);
                return null;
              }
            })
        .when(firstChannel)
        .basicConsume(
            anyString(),
            anyBoolean(),
            anyString(),
            anyBoolean(),
            anyBoolean(),
            anyMap(),
            any(Consumer.class));

    final CountDownLatch commitLatch = new CountDownLatch(1);
    doAnswer(
            new Answer<String>() {

              @Override
              public String answer(InvocationOnMock invocation) throws Throwable {
                commitLatch.countDown();
                return null;
              }
            })
        .when(firstChannel)
        .txCommit();

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Channel> exposed = new AtomicReference<Channel>();
    SimpleMessageListenerContainer container =
        new SimpleMessageListenerContainer(singleConnectionFactory);
    container.setMessageListener(
        new ChannelAwareMessageListener() {
          @Override
          public void onMessage(Message message, Channel channel) {
            exposed.set(channel);
            RabbitTemplate rabbitTemplate = new RabbitTemplate(singleConnectionFactory);
            rabbitTemplate.setChannelTransacted(true);
            // should use same channel as container
            rabbitTemplate.convertAndSend("foo", "bar", "baz");
            latch.countDown();
          }
        });
    container.setQueueNames("queue");
    container.setChannelTransacted(true);
    container.setExposeListenerChannel(false);
    container.setShutdownTimeout(100);
    container.afterPropertiesSet();
    container.start();

    consumer
        .get()
        .handleDelivery(
            "qux", new Envelope(1, false, "foo", "bar"), new BasicProperties(), new byte[] {0});

    assertTrue(latch.await(10, TimeUnit.SECONDS));

    Exception e = tooManyChannels.get();
    if (e != null) {
      throw e;
    }

    // once for listener, once for exposed + 0 for template (used bound)
    verify(mockConnection, Mockito.times(2)).createChannel();
    assertTrue(commitLatch.await(10, TimeUnit.SECONDS));
    verify(firstChannel).txCommit();
    verify(secondChannel).txCommit();
    verify(secondChannel)
        .basicPublish(
            Mockito.anyString(),
            Mockito.anyString(),
            Mockito.anyBoolean(),
            Mockito.any(BasicProperties.class),
            Mockito.any(byte[].class));

    assertSame(secondChannel, exposed.get());

    verify(firstChannel, Mockito.never()).close();
    verify(secondChannel, Mockito.times(1)).close();
    container.stop();
  }
  @Test
  public void testReplyToThreeDeepCustomCorrelationKey() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    final RabbitTemplate template =
        new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory));
    template.setCorrelationKey(CORRELATION_HEADER);
    Queue replyQueue = new Queue("replyTo2");
    template.setReplyQueue(replyQueue);

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setReplyTo("replyTo1");
    messageProperties.setCorrelationId("a".getBytes());
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    final AtomicInteger count = new AtomicInteger();
    final List<String> nestedReplyTo = new ArrayList<String>();
    final List<String> nestedCorrelation = new ArrayList<String>();
    doAnswer(
            new Answer<Object>() {
              public Object answer(InvocationOnMock invocation) throws Throwable {
                BasicProperties basicProps = (BasicProperties) invocation.getArguments()[4];
                nestedReplyTo.add(basicProps.getReplyTo());
                nestedCorrelation.add(basicProps.getCorrelationId());
                MessageProperties springProps =
                    new DefaultMessagePropertiesConverter()
                        .toMessageProperties(basicProps, null, "UTF-8");
                Message replyMessage = new Message("!dlrow olleH".getBytes(), springProps);
                if (count.incrementAndGet() < 2) {
                  Message anotherMessage = new Message("Second".getBytes(), springProps);
                  template.setReplyQueue(new Queue("replyTo3"));
                  replyMessage = template.sendAndReceive(anotherMessage);
                  nestedReplyTo.add(replyMessage.getMessageProperties().getReplyTo());
                  nestedCorrelation.add(
                      (String)
                          replyMessage.getMessageProperties().getHeaders().get(CORRELATION_HEADER));
                }
                template.onMessage(replyMessage);
                return null;
              }
            })
        .when(mockChannel)
        .basicPublish(
            Mockito.any(String.class),
            Mockito.any(String.class),
            Mockito.anyBoolean(),
            Mockito.anyBoolean(),
            Mockito.any(BasicProperties.class),
            Mockito.any(byte[].class));
    Message reply = template.sendAndReceive(message);
    assertNotNull(reply);

    assertEquals(3, nestedReplyTo.size());
    assertEquals("replyTo2", nestedReplyTo.get(0));
    assertEquals("replyTo3", nestedReplyTo.get(1));
    assertEquals("replyTo2", nestedReplyTo.get(2)); // intermediate reply

    assertEquals("replyTo1", reply.getMessageProperties().getReplyTo());
    assertEquals("a", new String(reply.getMessageProperties().getCorrelationId(), "UTF-8"));
  }
  @SuppressWarnings("serial")
  @Test
  public void testPagingAfterItem() throws Exception {
    Element rsm =
        new BaseElement(new QName("set", new Namespace("", "http://jabber.org/protocol/rsm")));

    GlobalItemID itemID =
        new GlobalItemIDImpl(new JID("capulet.lit"), "/user/[email protected]/posts", "item1");

    rsm.addElement("after").setText(itemID.toString());
    rsm.addElement("max").setText("5");

    element.addAttribute("node", node);

    Mockito.when(channelManager.nodeExists(anyString())).thenReturn(true);

    Mockito.when(channelManager.getNodeMembership(node, jid))
        .thenReturn(
            new NodeMembershipImpl(node, jid, Subscriptions.subscribed, Affiliations.member, null));

    ArrayList<NodeItem> results =
        new ArrayList<NodeItem>() {
          {
            add(
                new NodeItemImpl(
                    TEST_NODE_1,
                    "entry1",
                    new Date(System.currentTimeMillis()),
                    "<entry><id>entry1</id></entry>"));
            add(
                new NodeItemImpl(
                    TEST_NODE_2,
                    "entry2",
                    new Date(System.currentTimeMillis() - 100),
                    "<entry><id>entry2</id></entry>"));
          }
        };

    Mockito.when(
            channelManager.getUserFeedItems(
                Mockito.any(JID.class),
                Mockito.any(Date.class),
                Mockito.anyInt(),
                Mockito.any(GlobalItemID.class),
                Mockito.anyBoolean()))
        .thenReturn(new ClosableIteratorImpl<NodeItem>(results.iterator()));
    Mockito.when(
            channelManager.getCountUserFeedItems(
                Mockito.any(JID.class), Mockito.any(Date.class), Mockito.anyBoolean()))
        .thenReturn(100);

    userItemsGet.process(element, jid, request, rsm);

    verify(channelManager)
        .getUserFeedItems(eq(jid), any(Date.class), eq(5), eq(itemID), Mockito.anyBoolean());

    Packet p = queue.poll(100, TimeUnit.MILLISECONDS);

    // Check the response has a valid rsm element
    Element rsmOut = p.getElement().element("pubsub").element("set");

    assertEquals("Unexpected count returned", "100", rsmOut.element("count").getText());
    assertEquals(
        "Unexpected first returned", TEST_NODE_1 + ",entry1", rsmOut.element("first").getText());
    assertEquals(
        "Unexpected last returned", TEST_NODE_2 + ",entry2", rsmOut.element("last").getText());
  }