@Test
  public void testHandleFire() throws Exception {
    expect(rootJobSettings.getJobClass()).andReturn(TestRootJob.class.getName());

    Capture<String> capturedPath = newCapture();
    Capture<Msg> capturedMsg = newCapture();
    Capture<ActorRef> capturedSrcRef = newCapture();
    workerMock.sendMsg(
        EasyMock.capture(capturedPath),
        EasyMock.capture(capturedMsg),
        EasyMock.capture(capturedSrcRef));
    expectLastCall();

    workerMock.doSnapshot();
    expectLastCall();

    replayAll();

    RootJobFireHandler handler = new RootJobFireHandler(workerMock);

    handler.handleFire();

    verifyAll();

    assertThat(capturedPath.getValue(), is("/user/supervisor"));
    assertEquals(
        ((NewMsg) capturedMsg.getValue()).getJob().getJobProducerClass(),
        TestRootJobProducer.class);
    assertThat(capturedSrcRef.getValue(), is(self));
  }
  /**
   * Tests run of zipalign with correct parameters as well adding aligned file to artifacts
   *
   * @throws Exception
   */
  public void testDefaultRun() throws Exception {
    ZipalignMojo mojo = createMojo("zipalign-config-project3");

    MavenProject project = Whitebox.getInternalState(mojo, "project");
    project.setPackaging(AndroidExtension.APK);

    MavenProjectHelper projectHelper = EasyMock.createNiceMock(MavenProjectHelper.class);
    Capture<File> capturedParameter = new Capture<File>();
    projectHelper.attachArtifact(
        EasyMock.eq(project),
        EasyMock.eq(AndroidExtension.APK),
        EasyMock.eq("aligned"),
        EasyMock.capture(capturedParameter));
    Whitebox.setInternalState(mojo, "projectHelper", projectHelper);

    final CommandExecutor mockExecutor = PowerMock.createMock(CommandExecutor.class);
    PowerMock.replace(
            CommandExecutor.Factory.class.getDeclaredMethod("createDefaultCommmandExecutor"))
        .with(
            new InvocationHandler() {
              @Override
              public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return mockExecutor;
              }
            });

    Capture<List<String>> capturedFile = new Capture<List<String>>();
    mockExecutor.setLogger(EasyMock.anyObject(Log.class));
    mockExecutor.executeCommand(EasyMock.anyObject(String.class), EasyMock.capture(capturedFile));

    PowerMock.mockStatic(FileUtils.class);
    EasyMock.expect(FileUtils.fileExists("app-updated.apk")).andReturn(true);

    EasyMock.replay(projectHelper);
    PowerMock.replay(mockExecutor);
    PowerMock.replay(FileUtils.class);

    mojo.execute();

    PowerMock.verify(mockExecutor);
    List<String> parameters = capturedFile.getValue();
    List<String> parametersExpected = new ArrayList<String>();
    parametersExpected.add("-v");
    parametersExpected.add("-f");
    parametersExpected.add("4");
    parametersExpected.add("app.apk");
    parametersExpected.add("app-updated.apk");
    assertEquals("Zipalign arguments aren't as expected", parametersExpected, parameters);

    PowerMock.verify(projectHelper);
    assertEquals(
        "File should be same as expected",
        new File("app-updated.apk"),
        capturedParameter.getValue());

    // verify that all method were invoked
    PowerMock.verify(FileUtils.class);
  }
 private void expectConfigure() throws Exception {
   PowerMock.expectPrivate(
           store,
           "createKafkaBasedLog",
           EasyMock.capture(capturedTopic),
           EasyMock.capture(capturedProducerProps),
           EasyMock.capture(capturedConsumerProps),
           EasyMock.capture(capturedConsumedCallback))
       .andReturn(storeLog);
 }
 private ConsoleRowsSender createConsoleRowsSenderMock(
     Capture<ConsoleRow.Type> consoleRowTypeCapture, Capture<String> logMessageCapture) {
   ConsoleRowsSender consoleRowsSenderMock = EasyMock.createStrictMock(ConsoleRowsSender.class);
   if (consoleRowTypeCapture != null) {
     consoleRowsSenderMock.sendLogMessageAsConsoleRow(
         EasyMock.capture(consoleRowTypeCapture),
         EasyMock.capture(logMessageCapture),
         EasyMock.anyInt());
     EasyMock.expectLastCall();
   }
   consoleRowsSenderMock.sendLogFileWriteTriggerAsConsoleRow();
   EasyMock.expectLastCall();
   EasyMock.replay(consoleRowsSenderMock);
   return consoleRowsSenderMock;
 }
  private ComponentExecutionRelatedInstances createComponentExecutionRelatedInstances(
      Capture<ConsoleRow> consoleRowCapture) {
    ComponentExecutionStorageBridge compExeStorageBridgeMock =
        EasyMock.createStrictMock(ComponentExecutionStorageBridge.class);
    EasyMock.expect(compExeStorageBridgeMock.getComponentExecutionDataManagementId())
        .andStubReturn(DM_ID);
    EasyMock.replay(compExeStorageBridgeMock);

    ComponentExecutionRelatedStates compExeRelatedStates = new ComponentExecutionRelatedStates();
    compExeRelatedStates.executionCount.set(EXE_COUNT);
    compExeRelatedStates.consoleRowSequenceNumber.set(CONSOLE_ROW_SEQ_NUMBER);
    compExeRelatedStates.compHasSentConsoleRowLogMessages.set(true);

    batchingConsoleRowForwarderMock = EasyMock.createStrictMock(BatchingConsoleRowsForwarder.class);
    batchingConsoleRowForwarderMock.onConsoleRow(EasyMock.capture(consoleRowCapture));
    EasyMock.replay(batchingConsoleRowForwarderMock);

    ComponentExecutionRelatedInstances compExeRelatedInstances =
        new ComponentExecutionRelatedInstances();
    compExeRelatedInstances.compExeStorageBridge = compExeStorageBridgeMock;
    compExeRelatedInstances.compExeCtx = new ComponentExecutionContextDefaultStub();
    compExeRelatedInstances.compExeRelatedStates = compExeRelatedStates;
    compExeRelatedInstances.batchingConsoleRowsForwarder = batchingConsoleRowForwarderMock;

    return compExeRelatedInstances;
  }
 private ComponentStateMachine createComponentStateMachineEventForRuns(
     Capture<ComponentStateMachineEvent> compStateMachineEventCapture) {
   ComponentStateMachine compStateMachineMock =
       EasyMock.createStrictMock(ComponentStateMachine.class);
   compStateMachineMock.postEvent(EasyMock.capture(compStateMachineEventCapture));
   EasyMock.expectLastCall();
   EasyMock.replay(compStateMachineMock);
   return compStateMachineMock;
 }
Example #7
0
  @Test
  public void testGetCustomerWithConnection() throws Exception {
    CustomerDAO dao =
        EasyMock.createMockBuilder(CustomerDAO.class)
            .addMockedMethod("findCustomers", List.class, Connection.class)
            .createStrictMock();
    Customer customer = EasyMock.createStrictMock(Customer.class);
    Connection connection = EasyMock.createStrictMock(Connection.class);
    int custId = 322;
    List<ICustomer> customerList = new LinkedList<ICustomer>();
    customerList.add(customer);

    Capture<List<SearchConstraint>> capture = new Capture<List<SearchConstraint>>();
    EasyMock.expect(dao.findCustomers(EasyMock.capture(capture), EasyMock.eq(connection)))
        .andReturn(customerList);

    EasyMock.replay(dao, customer, connection);
    assertEquals("Wrong customer returned.", customer, dao.getCustomer(custId, connection));
    EasyMock.verify(dao, customer, connection);
    assertEquals("Wrong # of constraints.", 1, capture.getValue().size());
    SearchConstraint constraint = capture.getValue().get(0);
    assertEquals(
        "Wrong property in constraint.",
        ICustomerService.PROP_CUSTOMER_ID,
        constraint.getProperty());
    assertEquals(
        "Wrong operator in constraint.",
        SearchConstraintOperator.CONSTRAINT_EQUALS,
        constraint.getOperator());
    assertEquals("Wrong value in constraint.", custId, constraint.getValue());

    // no customers
    customerList.clear();
    EasyMock.reset(dao, customer, connection);
    capture = new Capture<List<SearchConstraint>>();
    EasyMock.expect(dao.findCustomers(EasyMock.capture(capture), EasyMock.eq(connection)))
        .andReturn(customerList);

    EasyMock.replay(dao, customer, connection);
    assertEquals(
        "Should not have found a customer returned.", null, dao.getCustomer(custId, connection));
    EasyMock.verify(dao, customer, connection);
  }
  @Test
  public void testGetCredentialsValidSession() {
    ComponentContext context = configureForSession();
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpSession session = createMock(HttpSession.class);
    EasyMock.expect(request.getSession(true)).andReturn(session);

    Principal principal = createMock(Principal.class);
    EasyMock.expect(request.getUserPrincipal()).andReturn(principal);
    EasyMock.expect(principal.getName()).andReturn(null);
    EasyMock.expect(request.getRemoteUser()).andReturn("ieb");
    Capture<SimpleCredentials> attributeValue = new Capture<SimpleCredentials>();
    Capture<String> attributeName = new Capture<String>();
    session.setAttribute(EasyMock.capture(attributeName), EasyMock.capture(attributeValue));

    HttpServletResponse response = createMock(HttpServletResponse.class);

    replay();
    trustedTokenService.activate(context);
    trustedTokenService.injectToken(request, response);
    Assert.assertTrue(attributeName.hasCaptured());
    Assert.assertTrue(attributeValue.hasCaptured());
    Credentials credentials = attributeValue.getValue();

    verify();
    reset();

    EasyMock.expect(request.getSession(false)).andReturn(session);
    EasyMock.expect(session.getAttribute(TrustedTokenService.SA_AUTHENTICATION_CREDENTIALS))
        .andReturn(credentials);

    replay();
    Credentials ieb = trustedTokenService.getCredentials(request, response);
    Assert.assertTrue(ieb instanceof SimpleCredentials);
    SimpleCredentials sc = (SimpleCredentials) ieb;
    TrustedUser tu = (TrustedUser) sc.getAttribute(TrustedTokenService.CA_AUTHENTICATION_USER);
    Assert.assertNotNull(tu);
    Assert.assertEquals("ieb", tu.getUser());
    verify();
  }
  @Test
  public void testSeedMetaTiled() throws Exception {
    WMSLayer layer = createWMSLayer("image/png");

    WMSSourceHelper mockSourceHelper = new MockWMSSourceHelper();
    MockLockProvider lockProvider = new MockLockProvider();
    layer.setSourceHelper(mockSourceHelper);
    layer.setLockProvider(lockProvider);

    final StorageBroker mockStorageBroker = EasyMock.createMock(StorageBroker.class);
    Capture<TileObject> captured = new Capture<TileObject>();
    expect(mockStorageBroker.put(EasyMock.capture(captured))).andReturn(true).anyTimes();
    replay(mockStorageBroker);

    String layerId = layer.getName();
    HttpServletRequest servletReq = new MockHttpServletRequest();
    HttpServletResponse servletResp = new MockHttpServletResponse();

    long[] gridLoc = {0, 0, 0}; // x, y, level
    MimeType mimeType = layer.getMimeTypes().get(0);
    GridSet gridSet = gridSetBroker.WORLD_EPSG4326;
    String gridSetId = gridSet.getName();
    ConveyorTile tile =
        new ConveyorTile(
            mockStorageBroker,
            layerId,
            gridSetId,
            gridLoc,
            mimeType,
            null,
            servletReq,
            servletResp);

    boolean tryCache = false;
    layer.seedTile(tile, tryCache);

    assertEquals(1, captured.getValues().size());
    TileObject value = captured.getValue();
    assertNotNull(value);
    assertEquals("image/png", value.getBlobFormat());
    assertNotNull(value.getBlob());
    assertTrue(value.getBlob().getSize() > 0);

    verify(mockStorageBroker);

    // check the lock provider was called in a symmetric way
    lockProvider.verify();
    lockProvider.clear();
  }
 private ComponentExecutionStorageBridge createComponentExecutionStorageBridgeNonRunFailure(
     ComponentExecutionRelatedInstances compExeRelatedInstancesStub, Integer exeCount)
     throws ComponentExecutionException {
   ComponentExecutionStorageBridge compExeStorageBridgeMock =
       EasyMock.createStrictMock(ComponentExecutionStorageBridge.class);
   EasyMock.expect(compExeStorageBridgeMock.hasUnfinishedComponentExecution()).andReturn(false);
   compExeStorageBridgeMock.addComponentExecution(
       compExeRelatedInstancesStub.compExeCtx, exeCount);
   EasyMock.expectLastCall();
   Capture<FinalComponentRunState> finalStateCapture = new Capture<>();
   compExeStorageBridgeMock.setComponentExecutionFinished(EasyMock.capture(finalStateCapture));
   EasyMock.expectLastCall();
   EasyMock.replay(compExeStorageBridgeMock);
   return compExeStorageBridgeMock;
 }
  @Test
  public void testAddCookie() {
    ComponentContext context = configureForCookie();
    HttpServletResponse response = createMock(HttpServletResponse.class);
    Capture<Cookie> cookieCapture = new Capture<Cookie>();
    response.addCookie(EasyMock.capture(cookieCapture));
    EasyMock.expectLastCall();

    replay();
    trustedTokenService.activate(context);
    trustedTokenService.addCookie(response, "ieb");
    Assert.assertTrue(cookieCapture.hasCaptured());
    Cookie cookie = cookieCapture.getValue();
    Assert.assertNotNull(cookie);
    Assert.assertEquals("secure-cookie", cookie.getName());
    String user = trustedTokenService.decodeCookie(cookie.getValue());
    Assert.assertEquals("ieb", user);
    verify();
  }
 @Test
 public void testCookieRefresh() throws InterruptedException {
   ComponentContext context = configureForCookieFast();
   HttpServletResponse response = createMock(HttpServletResponse.class);
   Capture<Cookie> cookieCapture = new Capture<Cookie>();
   response.addCookie(EasyMock.capture(cookieCapture));
   EasyMock.expectLastCall();
   replay();
   trustedTokenService.activate(context);
   String cookie = trustedTokenService.encodeCookie("ieb");
   Thread.sleep(100L);
   trustedTokenService.refreshToken(response, cookie, "ieb");
   Assert.assertTrue(cookieCapture.hasCaptured());
   Cookie cookie2 = cookieCapture.getValue();
   Assert.assertNotNull(cookie);
   Assert.assertNotSame(cookie, cookie2.getValue());
   Assert.assertEquals("secure-cookie", cookie2.getName());
   String user = trustedTokenService.decodeCookie(cookie2.getValue());
   Assert.assertEquals("ieb", user);
   verify();
 }
  @Test
  public void testInjectCookiePrincipal() {
    ComponentContext context = configureForCookie();
    HttpServletRequest request = createMock(HttpServletRequest.class);
    Principal principal = createMock(Principal.class);
    EasyMock.expect(request.getUserPrincipal()).andReturn(principal);
    EasyMock.expect(principal.getName()).andReturn("ieb");
    HttpServletResponse response = createMock(HttpServletResponse.class);
    Capture<Cookie> cookieCapture = new Capture<Cookie>();
    response.addCookie(EasyMock.capture(cookieCapture));
    EasyMock.expectLastCall();

    replay();
    trustedTokenService.activate(context);
    trustedTokenService.injectToken(request, response);
    Assert.assertTrue(cookieCapture.hasCaptured());
    Cookie cookie = cookieCapture.getValue();
    Assert.assertNotNull(cookie);
    Assert.assertEquals("secure-cookie", cookie.getName());
    String user = trustedTokenService.decodeCookie(cookie.getValue());
    Assert.assertEquals("ieb", user);
    verify();
  }
  @SuppressWarnings({"unchecked", "rawtypes"})
  private <T extends Request> RestRequest clientGeneratedRequest(
      Class<T> requestClass,
      ResourceMethod method,
      DataMap entityBody,
      RestClient.ContentType contentType,
      List<RestClient.AcceptType> acceptTypes)
      throws URISyntaxException {
    // massive setup...
    Client mockClient = EasyMock.createMock(Client.class);

    @SuppressWarnings({"rawtypes"})
    Request<?> mockRequest = EasyMock.createMock(requestClass);
    RecordTemplate mockRecordTemplate = EasyMock.createMock(RecordTemplate.class);
    @SuppressWarnings({"rawtypes"})
    RestResponseDecoder mockResponseDecoder = EasyMock.createMock(RestResponseDecoder.class);

    setCommonExpectations(mockRequest, method, mockRecordTemplate, mockResponseDecoder);

    if (method == ResourceMethod.BATCH_PARTIAL_UPDATE || method == ResourceMethod.BATCH_UPDATE) {
      buildInputForBatchPathAndUpdate(mockRequest);
    } else {
      EasyMock.expect(mockRequest.getInputRecord()).andReturn(mockRecordTemplate).times(2);
      EasyMock.expect(mockRequest.getResourceSpec()).andReturn(new ResourceSpecImpl()).once();
    }

    if (method == ResourceMethod.GET) {
      EasyMock.expect(((GetRequest) mockRequest).getObjectId()).andReturn(null).once();
      EasyMock.expect(((GetRequest) mockRequest).getResourceSpec())
          .andReturn(new ResourceSpecImpl())
          .once();
      EasyMock.expect(mockRequest.getMethodName()).andReturn(null);
    } else if (method == ResourceMethod.BATCH_GET) {
      EasyMock.expect(mockRequest.getMethodName()).andReturn(null);
    } else if (method == ResourceMethod.ACTION) {
      EasyMock.expect(((ActionRequest) mockRequest).getId()).andReturn(null);
      EasyMock.expect(mockRequest.getMethodName()).andReturn("testAction");
    } else if (method == ResourceMethod.FINDER) {
      EasyMock.expect(((FindRequest) mockRequest).getAssocKey()).andReturn(new CompoundKey());
      EasyMock.expect(mockRequest.getMethodName()).andReturn("testFinder");
    } else if (method == ResourceMethod.GET_ALL) {
      EasyMock.expect(((GetAllRequest) mockRequest).getAssocKey()).andReturn(new CompoundKey());
      EasyMock.expect(mockRequest.getMethodName()).andReturn(null);
    } else if (method == ResourceMethod.UPDATE) {
      EasyMock.expect(((UpdateRequest) mockRequest).getResourceSpec())
          .andReturn(new ResourceSpecImpl())
          .once();
      EasyMock.expect(((UpdateRequest) mockRequest).getId()).andReturn(null);
      EasyMock.expect(mockRequest.getMethodName()).andReturn(null);
    } else if (method == ResourceMethod.PARTIAL_UPDATE) {
      EasyMock.expect(mockRequest.getResourceSpec()).andReturn(new ResourceSpecImpl()).times(2);
      EasyMock.expect(((PartialUpdateRequest) mockRequest).getId()).andReturn(null);
      EasyMock.expect(mockRequest.getMethodName()).andReturn(null);
    } else if (method == ResourceMethod.DELETE) {
      EasyMock.expect(((DeleteRequest) mockRequest).getResourceSpec())
          .andReturn(new ResourceSpecImpl())
          .once();
      EasyMock.expect(((DeleteRequest) mockRequest).getId()).andReturn(null);
      EasyMock.expect(mockRequest.getMethodName()).andReturn(null);
    } else {
      EasyMock.expect(mockRequest.getMethodName()).andReturn(null);
    }

    EasyMock.expect(mockRecordTemplate.data()).andReturn(entityBody).once();

    Capture<RestRequest> restRequestCapture = new Capture<RestRequest>();

    EasyMock.expect(mockClient.getMetadata(new URI(HOST + SERVICE_NAME)))
        .andReturn(Collections.<String, Object>emptyMap())
        .once();

    mockClient.restRequest(
        EasyMock.capture(restRequestCapture),
        (RequestContext) EasyMock.anyObject(),
        (Callback<RestResponse>) EasyMock.anyObject());
    EasyMock.expectLastCall().once();

    EasyMock.replay(mockClient, mockRequest, mockRecordTemplate);

    // do work!
    RestClient restClient;
    if (acceptTypes == null) {
      restClient = new RestClient(mockClient, HOST);
    } else if (contentType == null) {
      restClient = new RestClient(mockClient, HOST, acceptTypes);
    } else {
      restClient = new RestClient(mockClient, HOST, contentType, acceptTypes);
    }

    restClient.sendRequest(mockRequest);

    return restRequestCapture.getValue();
  }
 /**
  * Creates a new CallbackCapture.
  *
  * @param <T> The type for the callback.
  * @param error The error to provide to the callback.
  * @return The CallbackCapture.
  */
 public static <T> Callback<T> callback(final Throwable error) {
   EasyMock.capture(new CallbackCapture<T>(error));
   return null;
 }
 private Capture<ItemRemoveEvent> captureRemoveEvent(ItemSetChangeListener removeListener) {
   Capture<ItemRemoveEvent> capturedEvent = new Capture<ItemRemoveEvent>();
   removeListener.containerItemSetChange(EasyMock.capture(capturedEvent));
   return capturedEvent;
 }
 private Capture<ItemAddEvent> captureAddEvent(ItemSetChangeListener addListener) {
   Capture<ItemAddEvent> capturedEvent = new Capture<ItemAddEvent>();
   addListener.containerItemSetChange(EasyMock.capture(capturedEvent));
   return capturedEvent;
 }
  @Test
  public void testSeedJpegPngMetaTiled() throws Exception {
    WMSLayer layer = createWMSLayer("image/vnd.jpeg-png");

    WMSSourceHelper mockSourceHelper =
        new WMSSourceHelper() {

          @Override
          protected void makeRequest(
              TileResponseReceiver tileRespRecv,
              WMSLayer layer,
              Map<String, String> wmsParams,
              MimeType expectedMimeType,
              Resource target)
              throws GeoWebCacheException {
            int width = Integer.parseInt(wmsParams.get("WIDTH"));
            int height = Integer.parseInt(wmsParams.get("HEIGHT"));
            assertEquals(768, width);
            assertEquals(768, height);
            BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D graphics = img.createGraphics();
            graphics.setColor(Color.BLACK);
            // fill an L shaped set of tiles, making a few partially filled
            graphics.fillRect(0, 0, width, 300);
            graphics.fillRect(0, 0, 300, height);
            graphics.dispose();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
              ImageIO.write(img, "PNG", output);
              ImageIO.write(img, "PNG", new java.io.File("/tmp/meta.png"));
            } catch (IOException e) {
              throw new RuntimeException(e);
            }

            try {
              target.transferFrom(
                  Channels.newChannel(new ByteArrayInputStream(output.toByteArray())));
            } catch (IOException e) {
              throw new RuntimeException(e);
            }
          }
        };
    MockLockProvider lockProvider = new MockLockProvider();
    layer.setSourceHelper(mockSourceHelper);
    layer.setLockProvider(lockProvider);

    final StorageBroker mockStorageBroker = EasyMock.createMock(StorageBroker.class);
    Capture<TileObject> captured = new Capture<TileObject>(CaptureType.ALL);
    expect(mockStorageBroker.put(EasyMock.capture(captured)))
        .andAnswer(
            new IAnswer<Boolean>() {

              @Override
              public Boolean answer() throws Throwable {
                TileObject to = (TileObject) EasyMock.getCurrentArguments()[0];
                assertEquals("image/vnd.jpeg-png", to.getBlobFormat());
                assertNotNull(to.getBlob());
                assertTrue(to.getBlob().getSize() > 0);
                String format = ImageMime.jpegPng.getMimeType(to.getBlob());
                long[] xyz = to.getXYZ();
                assertEquals(10, xyz[2]);
                // check the ones in the full black area are jpeg, the others png
                if (xyz[0] == 900 || xyz[1] == 602) {
                  assertEquals("image/jpeg", format);
                } else {
                  assertEquals("image/png", format);
                }

                return true;
              }
            })
        .anyTimes();
    replay(mockStorageBroker);

    String layerId = layer.getName();
    HttpServletRequest servletReq = new MockHttpServletRequest();
    HttpServletResponse servletResp = new MockHttpServletResponse();

    long[] gridLoc = {900, 600, 10}; // x, y, level
    MimeType mimeType = layer.getMimeTypes().get(0);
    GridSet gridSet = gridSetBroker.WORLD_EPSG4326;
    String gridSetId = gridSet.getName();
    ConveyorTile tile =
        new ConveyorTile(
            mockStorageBroker,
            layerId,
            gridSetId,
            gridLoc,
            mimeType,
            null,
            servletReq,
            servletResp);

    boolean tryCache = false;
    layer.seedTile(tile, tryCache);

    assertEquals(9, captured.getValues().size());
    verify(mockStorageBroker);

    // check the lock provider was called in a symmetric way
    lockProvider.verify();
    lockProvider.clear();
  }
  @SuppressWarnings("unchecked")
  @Test
  public void test()
      throws ServletException, IOException, UnsupportedRepositoryOperationException,
          RepositoryException {
    SlingHttpServletRequest request = createNiceMock(SlingHttpServletRequest.class);
    SlingHttpServletResponse response = createNiceMock(SlingHttpServletResponse.class);
    RequestPathInfo requestPathInfo = createNiceMock(RequestPathInfo.class);
    Resource resource = createNiceMock(Resource.class);
    Node node = createNiceMock(Node.class);
    VersionHistory versionHistory = createNiceMock(VersionHistory.class);
    Version version = createNiceMock(Version.class);
    Node frozenNode = createNiceMock(Node.class);
    Property resourceTypeProperty = createNiceMock(Property.class);
    Capture<Resource> capturedResource = new Capture<Resource>();
    RequestDispatcher requestDispatcher = createNiceMock(RequestDispatcher.class);
    Capture<ServletRequest> capturedRequest = new Capture<ServletRequest>();
    Capture<ServletResponse> capturedResponse = new Capture<ServletResponse>();
    VersionManager versionManager = createNiceMock(VersionManager.class);
    Session session = createNiceMock(Session.class);
    Workspace workspace = createNiceMock(Workspace.class);

    EasyMock.expect(request.getRequestPathInfo()).andReturn(requestPathInfo);
    EasyMock.expect(requestPathInfo.getSelectorString()).andReturn("version.,1.1,.tidy.json");
    EasyMock.expect(request.getResource()).andReturn(resource);
    EasyMock.expect(resource.adaptTo(Node.class)).andReturn(node);
    EasyMock.expect(node.getPath()).andReturn("/foo");
    EasyMock.expect(node.getSession()).andReturn(session);
    EasyMock.expect(session.getWorkspace()).andReturn(workspace);
    EasyMock.expect(workspace.getVersionManager()).andReturn(versionManager);
    EasyMock.expect(versionManager.getVersionHistory("/foo")).andReturn(versionHistory);
    EasyMock.expect(versionHistory.getVersion("1.1")).andReturn(version);
    EasyMock.expect(version.getNode(JcrConstants.JCR_FROZENNODE)).andReturn(frozenNode);
    EasyMock.expect(frozenNode.getPath()).andReturn("/testnode");
    EasyMock.expect(frozenNode.hasProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY))
        .andReturn(true);
    EasyMock.expect(frozenNode.getProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY))
        .andReturn(resourceTypeProperty);
    EasyMock.expect(resourceTypeProperty.getString()).andReturn("sakai/testing");
    EasyMock.expect(frozenNode.hasProperty(JcrResourceConstants.SLING_RESOURCE_SUPER_TYPE_PROPERTY))
        .andReturn(true);
    EasyMock.expect(frozenNode.getProperty(JcrResourceConstants.SLING_RESOURCE_SUPER_TYPE_PROPERTY))
        .andReturn(resourceTypeProperty);
    EasyMock.expect(resourceTypeProperty.getString()).andReturn("sakai/super-type-testing");
    EasyMock.expect(request.getRequestDispatcher(EasyMock.capture(capturedResource)))
        .andReturn(requestDispatcher);
    requestDispatcher.forward(
        EasyMock.capture(capturedRequest), EasyMock.capture(capturedResponse));
    EasyMock.expectLastCall();

    replay();
    getVersionServlet.doGet(request, response);

    Assert.assertTrue(capturedRequest.hasCaptured());
    Assert.assertTrue(capturedResource.hasCaptured());
    Assert.assertTrue(capturedResponse.hasCaptured());

    Resource cresource = capturedResource.getValue();

    Node capturedNode = cresource.adaptTo(Node.class);
    Assert.assertEquals(capturedNode, frozenNode);

    Map<String, String> map = cresource.adaptTo(Map.class);
    Assert.assertNotNull(map);

    verify();
  }
  @Test
  public void testSetFailure() throws Exception {
    expectConfigure();
    expectStart(Collections.EMPTY_LIST);
    expectStop();

    // Set offsets
    Capture<org.apache.kafka.clients.producer.Callback> callback0 = EasyMock.newCapture();
    storeLog.send(
        EasyMock.aryEq(TP0_KEY.array()),
        EasyMock.aryEq(TP0_VALUE.array()),
        EasyMock.capture(callback0));
    PowerMock.expectLastCall();
    Capture<org.apache.kafka.clients.producer.Callback> callback1 = EasyMock.newCapture();
    storeLog.send(
        EasyMock.aryEq(TP1_KEY.array()),
        EasyMock.aryEq(TP1_VALUE.array()),
        EasyMock.capture(callback1));
    PowerMock.expectLastCall();
    Capture<org.apache.kafka.clients.producer.Callback> callback2 = EasyMock.newCapture();
    storeLog.send(
        EasyMock.aryEq(TP2_KEY.array()),
        EasyMock.aryEq(TP2_VALUE.array()),
        EasyMock.capture(callback2));
    PowerMock.expectLastCall();

    PowerMock.replayAll();

    store.configure(DEFAULT_PROPS);
    store.start();

    // Set some offsets
    Map<ByteBuffer, ByteBuffer> toSet = new HashMap<>();
    toSet.put(TP0_KEY, TP0_VALUE);
    toSet.put(TP1_KEY, TP1_VALUE);
    toSet.put(TP2_KEY, TP2_VALUE);
    final AtomicBoolean invoked = new AtomicBoolean(false);
    final AtomicBoolean invokedFailure = new AtomicBoolean(false);
    Future<Void> setFuture =
        store.set(
            toSet,
            new Callback<Void>() {
              @Override
              public void onCompletion(Throwable error, Void result) {
                invoked.set(true);
                if (error != null) invokedFailure.set(true);
              }
            });
    assertFalse(setFuture.isDone());
    // Out of order callbacks shouldn't matter, should still require all to be invoked before
    // invoking the callback
    // for the store's set callback
    callback1.getValue().onCompletion(null, null);
    assertFalse(invoked.get());
    callback2.getValue().onCompletion(null, new KafkaException("bogus error"));
    assertTrue(invoked.get());
    assertTrue(invokedFailure.get());
    callback0.getValue().onCompletion(null, null);
    try {
      setFuture.get(10000, TimeUnit.MILLISECONDS);
      fail(
          "Should have seen KafkaException thrown when waiting on KafkaOffsetBackingStore.set() future");
    } catch (ExecutionException e) {
      // expected
      assertNotNull(e.getCause());
      assertTrue(e.getCause() instanceof KafkaException);
    }

    store.stop();

    PowerMock.verifyAll();
  }
  @Test
  public void testFilterResourcesCommand() {

    // Mock an ExecutionContext.
    ExecutionContext executionContext = EasyMock.createMock(ExecutionContext.class);
    EasyMock.replay(executionContext);

    // Create a mock DrawableFinder, just creates one drawable/density/resource dir.
    FilterResourcesCommand.DrawableFinder finder =
        EasyMock.createMock(FilterResourcesCommand.DrawableFinder.class);

    EasyMock.expect(finder.findDrawables(resDirectories))
        .andAnswer(
            new IAnswer<Set<String>>() {
              @SuppressWarnings("unchecked")
              @Override
              public Set<String> answer() throws Throwable {
                ImmutableSet.Builder<String> builder = ImmutableSet.builder();
                for (String dir : (Iterable<String>) EasyMock.getCurrentArguments()[0]) {
                  for (String qualifier : qualifiers) {
                    builder.add(
                        new File(dir, String.format("drawable-%s/some.png", qualifier)).getPath());
                  }
                }
                return builder.build();
              }
            })
        .times(2); // We're calling it in the test as well.
    EasyMock.replay(finder);

    // Create mock FilteredDirectoryCopier to find what we're calling on it.
    FilteredDirectoryCopier copier = EasyMock.createMock(FilteredDirectoryCopier.class);
    // We'll want to see what the filtering command passes to the copier.
    Capture<Map<String, String>> dirMapCapture = new Capture<Map<String, String>>();
    Capture<Predicate<File>> predCapture = new Capture<Predicate<File>>();
    copier.copyDirs(EasyMock.capture(dirMapCapture), EasyMock.capture(predCapture));
    EasyMock.expectLastCall().once();
    EasyMock.replay(copier);

    FilterResourcesCommand command =
        new FilterResourcesCommand(resDirectories, baseDestination, targetDensity, copier, finder);

    // We'll use this to verify the source->destination mappings created by the command.
    ImmutableMap.Builder<String, String> dirMapBuilder = ImmutableMap.builder();

    Iterator<String> destIterator = command.getFilteredResourceDirectories().iterator();
    for (String dir : resDirectories) {
      String nextDestination = destIterator.next();
      dirMapBuilder.put(dir, nextDestination);

      // Verify that destination path requirements are observed.
      assertEquals(baseDestination, new File(nextDestination).getParentFile());
    }

    // Execute command.
    command.execute(executionContext);

    // Ensure resources are copied to the right places.
    assertEquals(dirMapBuilder.build(), dirMapCapture.getValue());

    // Ensure the right filter is created.
    Set<String> drawables = finder.findDrawables(resDirectories);
    Predicate<File> expectedPred = Filters.createImageDensityFilter(drawables, targetDensity);
    Predicate<File> capturedPred = predCapture.getValue();
    for (String drawablePath : drawables) {
      File drawableFile = new File(drawablePath);
      assertEquals(expectedPred.apply(drawableFile), capturedPred.apply(drawableFile));
    }

    // We shouldn't need the execution context, should call copyDirs once on the copier,
    // and we're calling finder.findDrawables twice.
    EasyMock.verify(copier, executionContext, finder);
  }
Example #22
0
  @Test
  public void testFindCustomerByGuid() throws Exception {
    CustomerDAO dao =
        EasyMock.createMockBuilder(CustomerDAO.class)
            .addMockedMethod("findCustomers", List.class)
            .createStrictMock();

    // null guid
    EasyMock.replay(dao);
    try {
      dao.findCustomerByGuid(null, true);
      fail("Should have thrown an exception when null guid passed in.");
    } catch (IllegalArgumentException ex) {
      // expected
    }
    EasyMock.verify(dao);

    // no customer found
    EasyMock.reset(dao);
    boolean allowDeleted = true;
    String guid = "myGuid";
    Capture<List<SearchConstraint>> capture = new Capture<List<SearchConstraint>>();
    List<ICustomer> customerList = new LinkedList<ICustomer>();
    EasyMock.expect(dao.findCustomers(EasyMock.capture(capture))).andReturn(customerList);
    EasyMock.replay(dao);
    assertNull("Should not have found a customer.", dao.findCustomerByGuid(guid, allowDeleted));
    EasyMock.verify(dao);
    assertEquals("Wrong # of constraints.", 1, capture.getValue().size());
    SearchConstraint constraint = capture.getValue().get(0);
    assertEquals(
        "Wrong property in constraint.",
        ICustomerService.PROP_CLOUD_SERVICE_ANY_GUID,
        constraint.getProperty());
    assertEquals(
        "Wrong operator in constraint.",
        SearchConstraintOperator.CONSTRAINT_EQUALS,
        constraint.getOperator());
    assertEquals("Wrong value in constraint.", guid, constraint.getValue());

    // customer found and don't allow deleted
    EasyMock.reset(dao);
    allowDeleted = false;
    capture = new Capture<List<SearchConstraint>>();
    Customer customer = EasyMock.createStrictMock(Customer.class);
    customerList.add(customer);
    EasyMock.expect(dao.findCustomers(EasyMock.capture(capture))).andReturn(customerList);
    EasyMock.replay(dao);
    assertEquals(
        "Should have found customer.", customer, dao.findCustomerByGuid(guid, allowDeleted));
    EasyMock.verify(dao);
    assertEquals("Wrong # of constraints.", 1, capture.getValue().size());
    constraint = capture.getValue().get(0);
    assertEquals(
        "Wrong property in constraint.",
        ICustomerService.PROP_CLOUD_SERVICE_GUID,
        constraint.getProperty());
    assertEquals(
        "Wrong operator in constraint.",
        SearchConstraintOperator.CONSTRAINT_EQUALS,
        constraint.getOperator());
    assertEquals("Wrong value in constraint.", guid, constraint.getValue());
  }
  /**
   * Tests canceling of {@link Component#processInputs()} in failure case, that means {@link
   * Component#processInputs()} doesn't return within expected amount of time.
   *
   * @throws ComponentExecutionException on unexpected error
   * @throws ComponentException on unexpected error
   * @throws InterruptedException on unexpected error
   * @throws ExecutionException on unexpected error
   */
  @Test(timeout = TEST_TIMEOUT_500_MSEC)
  public void testCancelProcessingInputsFailure()
      throws ComponentExecutionException, ComponentException, InterruptedException,
          ExecutionException {

    ComponentExecutionRelatedInstances compExeRelatedInstancesStub =
        createComponentExecutionRelatedInstancesStub();

    final CountDownLatch processInputsCalledLatch = new CountDownLatch(1);
    Component compStub =
        new ComponentDefaultStub.Default() {

          private int processInputsCount = 0;

          private int onProcessInputsInterruptedCount = 0;

          @Override
          public void processInputs() throws ComponentException {
            if (processInputsCount > 0) {
              fail("'processInputs' is expected to be called only once");
            }
            processInputsCalledLatch.countDown();
            final CountDownLatch dummyLatch = new CountDownLatch(1);
            while (true) {
              try {
                dummyLatch.await();
              } catch (InterruptedException e) {
                // ignore for test purposes
                e = null;
              }
            }
          }

          @Override
          public void onProcessInputsInterrupted(ThreadHandler executingThreadHandler) {
            if (onProcessInputsInterruptedCount > 0) {
              fail("'onProcessInputsInterrupted' is expected to be called only once");
            }
          }
        };
    compExeRelatedInstancesStub.component.set(compStub);

    ComponentStateMachine compStateMachineMock =
        EasyMock.createStrictMock(ComponentStateMachine.class);
    Capture<ComponentStateMachineEvent> compStateMachineEventCapture = new Capture<>();
    compStateMachineMock.postEvent(EasyMock.capture(compStateMachineEventCapture));
    EasyMock.expectLastCall();
    EasyMock.replay(compStateMachineMock);
    compExeRelatedInstancesStub.compStateMachine = compStateMachineMock;

    ComponentExecutionStorageBridge compExeStorageBridgeMock =
        createComponentExecutionStorageBridgeRunFailure(compExeRelatedInstancesStub);
    compExeRelatedInstancesStub.compExeStorageBridge = compExeStorageBridgeMock;

    ComponentContextBridge compCtxBridgeMock =
        EasyMock.createStrictMock(ComponentContextBridge.class);
    EasyMock.expect(compCtxBridgeMock.getEndpointDatumsForExecution())
        .andStubReturn(new HashMap<String, EndpointDatum>());
    EasyMock.replay(compCtxBridgeMock);
    compExeRelatedInstancesStub.compCtxBridge = compCtxBridgeMock;

    compExeRelatedInstancesStub.compExeScheduler = createComponentExecutionSchedulerMock(false);

    Capture<ConsoleRow.Type> consoleRowTypeCapture = new Capture<>();
    Capture<String> logMessageCapture = new Capture<>();
    ConsoleRowsSender consoleRowsSenderMock =
        createConsoleRowsSenderMock(consoleRowTypeCapture, logMessageCapture);
    compExeRelatedInstancesStub.consoleRowsSender = consoleRowsSenderMock;

    ComponentExecutionStatsService compExeStatsServiceMock =
        createComponentExecutionStatsServiceMock(compExeRelatedInstancesStub);

    final ComponentExecutor compExecutor =
        new ComponentExecutor(compExeRelatedInstancesStub, ComponentExecutionType.ProcessInputs);
    compExecutor.bindComponentExecutionPermitsService(createComponentExecutionPermitServiceMock());
    compExecutor.bindComponentExecutionStatsService(compExeStatsServiceMock);
    ComponentExecutor.waitIntervalAfterCacelledCalledMSec = WAIT_INTERVAL_100_MSEC;

    final AtomicReference<Exception> expectedExceptionRef = new AtomicReference<Exception>(null);

    final CountDownLatch executedLatch = new CountDownLatch(1);
    final Future<?> executeTask =
        ConcurrencyUtils.getAsyncTaskService()
            .submit(
                new Runnable() {

                  @Override
                  public void run() {
                    try {
                      compExecutor.executeByConsideringLimitations();
                    } catch (ComponentException | ComponentExecutionException e) {
                      expectedExceptionRef.set(e);
                    }
                    executedLatch.countDown();
                  }
                });
    processInputsCalledLatch.await();
    compExecutor.onCancelled();
    executeTask.cancel(true);

    executedLatch.await();

    assertNotNull(expectedExceptionRef.get());
    assertTrue(expectedExceptionRef.get() instanceof ComponentException);
    assertFailureHandling(
        consoleRowTypeCapture,
        logMessageCapture,
        (ComponentException) expectedExceptionRef.get(),
        "didn't terminate in time");

    assertTrue(compExeRelatedInstancesStub.compExeRelatedStates.isComponentCancelled.get());
    EasyMock.verify(compStateMachineMock);
    assertEquals(
        ComponentStateMachineEventType.RUNNING, compStateMachineEventCapture.getValue().getType());
    assertEquals(
        ComponentState.PROCESSING_INPUTS,
        compStateMachineEventCapture.getValue().getNewComponentState());
    EasyMock.verify(compExeStorageBridgeMock);
    EasyMock.verify(consoleRowsSenderMock);
  }
 /**
  * Creates a new CallbackCapture.
  *
  * @param <T> The type for the callback.
  * @param value The value to provide to the callback.
  * @return The CallbackCapture.
  */
 public static <T> Callback<T> callback(final T value) {
   EasyMock.capture(new CallbackCapture<T>(value));
   return null;
 }
Example #25
0
  @Test
  public void testQueryInterruptionExceptionLogMessage() throws JsonProcessingException {
    HttpClient httpClient = EasyMock.createMock(HttpClient.class);
    SettableFuture<Object> interruptionFuture = SettableFuture.create();
    Capture<Request> capturedRequest = EasyMock.newCapture();
    String hostName = "localhost:8080";
    EasyMock.expect(
            httpClient.go(
                EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject()))
        .andReturn(interruptionFuture)
        .anyTimes();

    EasyMock.replay(httpClient);

    DataSegment dataSegment =
        new DataSegment(
            "test",
            new Interval("2013-01-01/2013-01-02"),
            new DateTime("2013-01-01").toString(),
            Maps.<String, Object>newHashMap(),
            Lists.<String>newArrayList(),
            Lists.<String>newArrayList(),
            NoneShardSpec.instance(),
            0,
            0L);
    final ServerSelector serverSelector =
        new ServerSelector(
            dataSegment,
            new HighestPriorityTierSelectorStrategy(new ConnectionCountServerSelectorStrategy()));

    DirectDruidClient client1 =
        new DirectDruidClient(
            new ReflectionQueryToolChestWarehouse(),
            QueryRunnerTestHelper.NOOP_QUERYWATCHER,
            new DefaultObjectMapper(),
            httpClient,
            hostName,
            new NoopServiceEmitter());

    QueryableDruidServer queryableDruidServer =
        new QueryableDruidServer(
            new DruidServer("test1", hostName, 0, "historical", DruidServer.DEFAULT_TIER, 0),
            client1);

    serverSelector.addServerAndUpdateSegment(queryableDruidServer, dataSegment);

    TimeBoundaryQuery query = Druids.newTimeBoundaryQueryBuilder().dataSource("test").build();
    HashMap<String, List> context = Maps.newHashMap();
    interruptionFuture.set(new ByteArrayInputStream("{\"error\":\"testing\"}".getBytes()));
    Sequence results = client1.run(query, context);

    QueryInterruptedException actualException = null;
    try {
      Sequences.toList(results, Lists.newArrayList());
    } catch (QueryInterruptedException e) {
      actualException = e;
    }
    Assert.assertNotNull(actualException);
    Assert.assertEquals(actualException.getMessage(), QueryInterruptedException.UNKNOWN_EXCEPTION);
    Assert.assertEquals(actualException.getCauseMessage(), "testing");
    Assert.assertEquals(actualException.getHost(), hostName);
    EasyMock.verify(httpClient);
  }
  @Test
  public void testGetSet() throws Exception {
    expectConfigure();
    expectStart(Collections.EMPTY_LIST);
    expectStop();

    // First get() against an empty store
    final Capture<Callback<Void>> firstGetReadToEndCallback = EasyMock.newCapture();
    storeLog.readToEnd(EasyMock.capture(firstGetReadToEndCallback));
    PowerMock.expectLastCall()
        .andAnswer(
            new IAnswer<Object>() {
              @Override
              public Object answer() throws Throwable {
                firstGetReadToEndCallback.getValue().onCompletion(null, null);
                return null;
              }
            });

    // Set offsets
    Capture<org.apache.kafka.clients.producer.Callback> callback0 = EasyMock.newCapture();
    storeLog.send(
        EasyMock.aryEq(TP0_KEY.array()),
        EasyMock.aryEq(TP0_VALUE.array()),
        EasyMock.capture(callback0));
    PowerMock.expectLastCall();
    Capture<org.apache.kafka.clients.producer.Callback> callback1 = EasyMock.newCapture();
    storeLog.send(
        EasyMock.aryEq(TP1_KEY.array()),
        EasyMock.aryEq(TP1_VALUE.array()),
        EasyMock.capture(callback1));
    PowerMock.expectLastCall();

    // Second get() should get the produced data and return the new values
    final Capture<Callback<Void>> secondGetReadToEndCallback = EasyMock.newCapture();
    storeLog.readToEnd(EasyMock.capture(secondGetReadToEndCallback));
    PowerMock.expectLastCall()
        .andAnswer(
            new IAnswer<Object>() {
              @Override
              public Object answer() throws Throwable {
                capturedConsumedCallback
                    .getValue()
                    .onCompletion(
                        null,
                        new ConsumerRecord<>(TOPIC, 0, 0, TP0_KEY.array(), TP0_VALUE.array()));
                capturedConsumedCallback
                    .getValue()
                    .onCompletion(
                        null,
                        new ConsumerRecord<>(TOPIC, 1, 0, TP1_KEY.array(), TP1_VALUE.array()));
                secondGetReadToEndCallback.getValue().onCompletion(null, null);
                return null;
              }
            });

    // Third get() should pick up data produced by someone else and return those values
    final Capture<Callback<Void>> thirdGetReadToEndCallback = EasyMock.newCapture();
    storeLog.readToEnd(EasyMock.capture(thirdGetReadToEndCallback));
    PowerMock.expectLastCall()
        .andAnswer(
            new IAnswer<Object>() {
              @Override
              public Object answer() throws Throwable {
                capturedConsumedCallback
                    .getValue()
                    .onCompletion(
                        null,
                        new ConsumerRecord<>(TOPIC, 0, 1, TP0_KEY.array(), TP0_VALUE_NEW.array()));
                capturedConsumedCallback
                    .getValue()
                    .onCompletion(
                        null,
                        new ConsumerRecord<>(TOPIC, 1, 1, TP1_KEY.array(), TP1_VALUE_NEW.array()));
                thirdGetReadToEndCallback.getValue().onCompletion(null, null);
                return null;
              }
            });

    PowerMock.replayAll();

    store.configure(DEFAULT_PROPS);
    store.start();

    // Getting from empty store should return nulls
    final AtomicBoolean getInvokedAndPassed = new AtomicBoolean(false);
    store
        .get(
            Arrays.asList(TP0_KEY, TP1_KEY),
            new Callback<Map<ByteBuffer, ByteBuffer>>() {
              @Override
              public void onCompletion(Throwable error, Map<ByteBuffer, ByteBuffer> result) {
                // Since we didn't read them yet, these will be null
                assertEquals(null, result.get(TP0_KEY));
                assertEquals(null, result.get(TP1_KEY));
                getInvokedAndPassed.set(true);
              }
            })
        .get(10000, TimeUnit.MILLISECONDS);
    assertTrue(getInvokedAndPassed.get());

    // Set some offsets
    Map<ByteBuffer, ByteBuffer> toSet = new HashMap<>();
    toSet.put(TP0_KEY, TP0_VALUE);
    toSet.put(TP1_KEY, TP1_VALUE);
    final AtomicBoolean invoked = new AtomicBoolean(false);
    Future<Void> setFuture =
        store.set(
            toSet,
            new Callback<Void>() {
              @Override
              public void onCompletion(Throwable error, Void result) {
                invoked.set(true);
              }
            });
    assertFalse(setFuture.isDone());
    // Out of order callbacks shouldn't matter, should still require all to be invoked before
    // invoking the callback
    // for the store's set callback
    callback1.getValue().onCompletion(null, null);
    assertFalse(invoked.get());
    callback0.getValue().onCompletion(null, null);
    setFuture.get(10000, TimeUnit.MILLISECONDS);
    assertTrue(invoked.get());

    // Getting data should read to end of our published data and return it
    final AtomicBoolean secondGetInvokedAndPassed = new AtomicBoolean(false);
    store
        .get(
            Arrays.asList(TP0_KEY, TP1_KEY),
            new Callback<Map<ByteBuffer, ByteBuffer>>() {
              @Override
              public void onCompletion(Throwable error, Map<ByteBuffer, ByteBuffer> result) {
                assertEquals(TP0_VALUE, result.get(TP0_KEY));
                assertEquals(TP1_VALUE, result.get(TP1_KEY));
                secondGetInvokedAndPassed.set(true);
              }
            })
        .get(10000, TimeUnit.MILLISECONDS);
    assertTrue(secondGetInvokedAndPassed.get());

    // Getting data should read to end of our published data and return it
    final AtomicBoolean thirdGetInvokedAndPassed = new AtomicBoolean(false);
    store
        .get(
            Arrays.asList(TP0_KEY, TP1_KEY),
            new Callback<Map<ByteBuffer, ByteBuffer>>() {
              @Override
              public void onCompletion(Throwable error, Map<ByteBuffer, ByteBuffer> result) {
                assertEquals(TP0_VALUE_NEW, result.get(TP0_KEY));
                assertEquals(TP1_VALUE_NEW, result.get(TP1_KEY));
                thirdGetInvokedAndPassed.set(true);
              }
            })
        .get(10000, TimeUnit.MILLISECONDS);
    assertTrue(thirdGetInvokedAndPassed.get());

    store.stop();

    PowerMock.verifyAll();
  }
Example #27
0
  @Test
  public void testRun() throws Exception {
    HttpClient httpClient = EasyMock.createMock(HttpClient.class);
    final URL url = new URL("http://foo/druid/v2/");

    SettableFuture<InputStream> futureResult = SettableFuture.create();
    Capture<Request> capturedRequest = EasyMock.newCapture();
    EasyMock.expect(
            httpClient.go(
                EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject()))
        .andReturn(futureResult)
        .times(1);

    SettableFuture futureException = SettableFuture.create();
    EasyMock.expect(
            httpClient.go(
                EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject()))
        .andReturn(futureException)
        .times(1);

    EasyMock.expect(
            httpClient.go(
                EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject()))
        .andReturn(SettableFuture.create())
        .atLeastOnce();

    EasyMock.replay(httpClient);

    final ServerSelector serverSelector =
        new ServerSelector(
            new DataSegment(
                "test",
                new Interval("2013-01-01/2013-01-02"),
                new DateTime("2013-01-01").toString(),
                Maps.<String, Object>newHashMap(),
                Lists.<String>newArrayList(),
                Lists.<String>newArrayList(),
                NoneShardSpec.instance(),
                0,
                0L),
            new HighestPriorityTierSelectorStrategy(new ConnectionCountServerSelectorStrategy()));

    DirectDruidClient client1 =
        new DirectDruidClient(
            new ReflectionQueryToolChestWarehouse(),
            QueryRunnerTestHelper.NOOP_QUERYWATCHER,
            new DefaultObjectMapper(),
            httpClient,
            "foo",
            new NoopServiceEmitter());
    DirectDruidClient client2 =
        new DirectDruidClient(
            new ReflectionQueryToolChestWarehouse(),
            QueryRunnerTestHelper.NOOP_QUERYWATCHER,
            new DefaultObjectMapper(),
            httpClient,
            "foo2",
            new NoopServiceEmitter());

    QueryableDruidServer queryableDruidServer1 =
        new QueryableDruidServer(
            new DruidServer("test1", "localhost", 0, "historical", DruidServer.DEFAULT_TIER, 0),
            client1);
    serverSelector.addServerAndUpdateSegment(queryableDruidServer1, serverSelector.getSegment());
    QueryableDruidServer queryableDruidServer2 =
        new QueryableDruidServer(
            new DruidServer("test1", "localhost", 0, "historical", DruidServer.DEFAULT_TIER, 0),
            client2);
    serverSelector.addServerAndUpdateSegment(queryableDruidServer2, serverSelector.getSegment());

    TimeBoundaryQuery query = Druids.newTimeBoundaryQueryBuilder().dataSource("test").build();
    HashMap<String, List> context = Maps.newHashMap();
    Sequence s1 = client1.run(query, context);
    Assert.assertTrue(capturedRequest.hasCaptured());
    Assert.assertEquals(url, capturedRequest.getValue().getUrl());
    Assert.assertEquals(HttpMethod.POST, capturedRequest.getValue().getMethod());
    Assert.assertEquals(1, client1.getNumOpenConnections());

    // simulate read timeout
    Sequence s2 = client1.run(query, context);
    Assert.assertEquals(2, client1.getNumOpenConnections());
    futureException.setException(new ReadTimeoutException());
    Assert.assertEquals(1, client1.getNumOpenConnections());

    // subsequent connections should work
    Sequence s3 = client1.run(query, context);
    Sequence s4 = client1.run(query, context);
    Sequence s5 = client1.run(query, context);

    Assert.assertTrue(client1.getNumOpenConnections() == 4);

    // produce result for first connection
    futureResult.set(
        new ByteArrayInputStream(
            "[{\"timestamp\":\"2014-01-01T01:02:03Z\", \"result\": 42.0}]".getBytes()));
    List<Result> results = Sequences.toList(s1, Lists.<Result>newArrayList());
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(new DateTime("2014-01-01T01:02:03Z"), results.get(0).getTimestamp());
    Assert.assertEquals(3, client1.getNumOpenConnections());

    client2.run(query, context);
    client2.run(query, context);

    Assert.assertTrue(client2.getNumOpenConnections() == 2);

    Assert.assertTrue(serverSelector.pick() == queryableDruidServer2);

    EasyMock.verify(httpClient);
  }
Example #28
0
  @Test
  public void testCancel() throws Exception {
    HttpClient httpClient = EasyMock.createStrictMock(HttpClient.class);

    Capture<Request> capturedRequest = EasyMock.newCapture();
    ListenableFuture<Object> cancelledFuture = Futures.immediateCancelledFuture();
    SettableFuture<Object> cancellationFuture = SettableFuture.create();

    EasyMock.expect(
            httpClient.go(
                EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject()))
        .andReturn(cancelledFuture)
        .once();

    EasyMock.expect(
            httpClient.go(
                EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject()))
        .andReturn(cancellationFuture)
        .once();

    EasyMock.replay(httpClient);

    final ServerSelector serverSelector =
        new ServerSelector(
            new DataSegment(
                "test",
                new Interval("2013-01-01/2013-01-02"),
                new DateTime("2013-01-01").toString(),
                Maps.<String, Object>newHashMap(),
                Lists.<String>newArrayList(),
                Lists.<String>newArrayList(),
                NoneShardSpec.instance(),
                0,
                0L),
            new HighestPriorityTierSelectorStrategy(new ConnectionCountServerSelectorStrategy()));

    DirectDruidClient client1 =
        new DirectDruidClient(
            new ReflectionQueryToolChestWarehouse(),
            QueryRunnerTestHelper.NOOP_QUERYWATCHER,
            new DefaultObjectMapper(),
            httpClient,
            "foo",
            new NoopServiceEmitter());

    QueryableDruidServer queryableDruidServer1 =
        new QueryableDruidServer(
            new DruidServer("test1", "localhost", 0, "historical", DruidServer.DEFAULT_TIER, 0),
            client1);
    serverSelector.addServerAndUpdateSegment(queryableDruidServer1, serverSelector.getSegment());

    TimeBoundaryQuery query = Druids.newTimeBoundaryQueryBuilder().dataSource("test").build();
    HashMap<String, List> context = Maps.newHashMap();
    cancellationFuture.set(
        new StatusResponseHolder(HttpResponseStatus.OK, new StringBuilder("cancelled")));
    Sequence results = client1.run(query, context);
    Assert.assertEquals(HttpMethod.DELETE, capturedRequest.getValue().getMethod());
    Assert.assertEquals(0, client1.getNumOpenConnections());

    QueryInterruptedException exception = null;
    try {
      Sequences.toList(results, Lists.newArrayList());
    } catch (QueryInterruptedException e) {
      exception = e;
    }
    Assert.assertNotNull(exception);

    EasyMock.verify(httpClient);
  }
 /**
  * Creates a new CallbackCapture.
  *
  * @param <T> The type for the callback.
  * @return The CallbackCapture.
  */
 public static <T> Callback<T> callbackError() {
   EasyMock.capture(new CallbackCapture<T>(new Throwable("Injected")));
   return null;
 }