/** @throws Exception */
  @Test(expected = EnvironmentConfigException.class)
  public void testReadConfig_JNDI_EnvironmentConfigException() throws Exception {
    // 建立私有方法的mock对象
    ConfigParamManager mock =
        PowerMock.createPartialMock(ConfigParamManager.class, "getConfigType");
    // 录制私有方法行为
    PowerMock.expectPrivate(mock, "getConfigType", EasyMock.anyObject(Document.class))
        .andReturn("JNDI");

    // 建立mock对象
    Document mockDocument = EasyMock.createMock(Document.class);
    // Document a = PowerMock.createMock(Document.class);
    // 录制public方法行为
    EasyMock.expect(mockDocument.getElementsByTagName(EasyMock.anyObject(String.class)))
        .andReturn(null);

    // 回放mock对象行为
    PowerMock.replay(mock);
    // 回放mock对象行为
    EasyMock.replay(mockDocument);

    EnvConfigBean envConfig = mock.readConfig(configLocation);

    PowerMock.verifyAll();
    EasyMock.verify(mockDocument);
  }
  @Test
  public void testSetIsInFields_first_ok_second_null_isInAlreadyFilled() {
    OpenStreetMapSimpleImporter openStreetMapSimpleImporter = new OpenStreetMapSimpleImporter();

    final String cityName = "cityName";
    final Integer population = 123;
    final String adm2name = "adm2name";
    final City city = new City();
    city.setPopulation(population);
    city.setAdm2Name(adm2name);
    city.setName(cityName);
    city.setMunicipality(false);
    city.setFeatureId(1L);
    city.setId(123L);
    final Set<ZipCode> zipCodes = new HashSet<ZipCode>();
    zipCodes.add(new ZipCode("zip1"));
    city.addZipCodes(zipCodes);
    Point location = GeolocHelper.createPoint(2F, 3F);

    String countryCode = "FR";

    AlternateName an1 = new AlternateName("an1", AlternateNameSource.OPENSTREETMAP);
    AlternateName an2 = new AlternateName("an2", AlternateNameSource.OPENSTREETMAP);
    city.addAlternateName(an1);
    city.addAlternateName(an2);

    ICityDao cityDao = EasyMock.createMock(ICityDao.class);
    EasyMock.expect(
            cityDao.getByShape(
                EasyMock.anyObject(Point.class),
                EasyMock.anyObject(String.class),
                EasyMock.eq(true)))
        .andReturn(null);
    EasyMock.expect(
            cityDao.getNearest(location, countryCode, true, OpenStreetMapSimpleImporter.DISTANCE))
        .andReturn(city);
    EasyMock.expect(
            cityDao.getNearest(location, countryCode, false, OpenStreetMapSimpleImporter.DISTANCE))
        .andReturn(null);
    EasyMock.replay(cityDao);
    openStreetMapSimpleImporter.setCityDao(cityDao);

    OpenStreetMap street = new OpenStreetMap();
    street.setCountryCode(countryCode);
    street.setLocation(location);
    street.setIsIn("AlreadyFilled");
    street.setCityId(456L);
    openStreetMapSimpleImporter.setIsInFields(street);

    Set<String> expectedZip = new HashSet<String>();
    expectedZip.add("ZIP1");
    Assert.assertEquals(expectedZip, street.getIsInZip());
    Assert.assertEquals("adm2name", street.getIsInAdm());
    Assert.assertEquals("AlreadyFilled", street.getIsIn());
    Assert.assertEquals(456L, street.getCityId());
    Assert.assertEquals(null, street.getIsInPlace());
    Assert.assertTrue(street.getIsInCityAlternateNames().size() == 2);

    EasyMock.verify(cityDao);
  }
  @Test(timeout = 4000L)
  public void testRealtimeIndexTaskFailure() throws Exception {
    setUpAndStartTaskQueue(
        new DataSegmentPusher() {
          @Override
          public String getPathForHadoop(String s) {
            throw new UnsupportedOperationException();
          }

          @Override
          public DataSegment push(File file, DataSegment dataSegment) throws IOException {
            throw new RuntimeException("FAILURE");
          }
        });
    monitorScheduler.addMonitor(EasyMock.anyObject(Monitor.class));
    EasyMock.expectLastCall().atLeastOnce();
    monitorScheduler.removeMonitor(EasyMock.anyObject(Monitor.class));
    EasyMock.expectLastCall().anyTimes();
    EasyMock.replay(monitorScheduler, queryRunnerFactoryConglomerate);

    RealtimeIndexTask realtimeIndexTask = giveMeARealtimeIndexTask();
    final String taskId = realtimeIndexTask.getId();
    tq.add(realtimeIndexTask);

    // Wait for realtime index task to fail
    while (tsqa.getStatus(taskId).get().isRunnable()) {
      Thread.sleep(10);
    }

    Assert.assertTrue("Task should be in Failure state", tsqa.getStatus(taskId).get().isFailure());

    EasyMock.verify(monitorScheduler, queryRunnerFactoryConglomerate);
  }
 private Capture<IScheduledTask> expectTaskScheduled(IScheduledTask task) {
   TaskInfo mesosTask = makeTaskInfo(task);
   Capture<IScheduledTask> taskScheduled = createCapture();
   expect(assigner.maybeAssign(EasyMock.<Offer>anyObject(), capture(taskScheduled)))
       .andReturn(Optional.of(mesosTask));
   driver.launchTask(EasyMock.<OfferID>anyObject(), eq(mesosTask));
   return taskScheduled;
 }
  /**
   * 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);
  }
  protected void insertPublisherInfoBehavior() {
    loader = new DataLoader(configLocation, executableLocation);

    // configure IExecutableAdvice
    LauncherData launcherData = loader.getLauncherData();
    LaunchingAdvice launchingAdvice = new LaunchingAdvice(launcherData, configSpec);

    ArrayList launchingList = new ArrayList();
    launchingList.add(launchingAdvice);

    ProductFileAdvice productAdvice = null;

    try {
      String productFileLocation =
          TestData.getFile("ProductActionTest", "productFileActionTest.product")
              .toString(); //$NON-NLS-1$ //$NON-NLS-2$
      productAdvice = new ProductFileAdvice(new ProductFile(productFileLocation), configSpec);
      launchingList.add(productAdvice);
    } catch (Exception e) {
      fail("Unable to create product file advice", e); // $NON-NLS-1$
    }

    expect(
            publisherInfo.getAdvice(
                EasyMock.matches(configSpec),
                EasyMock.eq(false),
                (String) EasyMock.anyObject(),
                (Version) EasyMock.anyObject(),
                EasyMock.eq(IExecutableAdvice.class)))
        .andReturn(launchingList)
        .anyTimes();

    // configure IConfigAdvice
    ConfigData configData = loader.getConfigData();
    ConfigAdvice configAdvice = new ConfigAdvice(configData, configSpec);
    ArrayList configList = new ArrayList();
    configList.add(configAdvice);
    configList.add(productAdvice);
    expect(
            publisherInfo.getAdvice(
                EasyMock.matches(configSpec),
                EasyMock.eq(false),
                (String) EasyMock.anyObject(),
                (Version) EasyMock.anyObject(),
                EasyMock.eq(IConfigAdvice.class)))
        .andReturn(configList)
        .anyTimes();

    // setup metadata repository
    IInstallableUnit[] ius = {
      mockIU("foo", null), mockIU("bar", null)
    }; //$NON-NLS-1$ //$NON-NLS-2$

    metadataRepo = new TestMetadataRepository(getAgent(), ius);
    expect(publisherInfo.getMetadataRepository()).andReturn(metadataRepo).anyTimes();
    expect(publisherInfo.getContextMetadataRepository()).andReturn(null).anyTimes();
  }
  @Before
  public void setUp() {
    volMgr = createMock(VolumeManager.class);
    instance = createMock(Instance.class);
    SiteConfiguration siteConfig = EasyMock.createMock(SiteConfiguration.class);
    expect(instance.getInstanceID()).andReturn("mock").anyTimes();
    expect(instance.getZooKeepers()).andReturn("localhost").anyTimes();
    expect(instance.getZooKeepersSessionTimeOut()).andReturn(30000).anyTimes();

    opts = new Opts();
    systemConfig = createSystemConfig();
    ServerConfigurationFactory factory = createMock(ServerConfigurationFactory.class);
    expect(factory.getInstance()).andReturn(instance).anyTimes();
    expect(factory.getConfiguration()).andReturn(systemConfig).anyTimes();
    expect(factory.getSiteConfiguration()).andReturn(siteConfig).anyTimes();

    // Just make the SiteConfiguration delegate to our AccumuloConfiguration
    // Presently, we only need get(Property) and iterator().
    EasyMock.expect(siteConfig.get(EasyMock.anyObject(Property.class)))
        .andAnswer(
            new IAnswer<String>() {
              @Override
              public String answer() {
                Object[] args = EasyMock.getCurrentArguments();
                return systemConfig.get((Property) args[0]);
              }
            })
        .anyTimes();
    EasyMock.expect(siteConfig.getBoolean(EasyMock.anyObject(Property.class)))
        .andAnswer(
            new IAnswer<Boolean>() {
              @Override
              public Boolean answer() {
                Object[] args = EasyMock.getCurrentArguments();
                return systemConfig.getBoolean((Property) args[0]);
              }
            })
        .anyTimes();

    EasyMock.expect(siteConfig.iterator())
        .andAnswer(
            new IAnswer<Iterator<Entry<String, String>>>() {
              @Override
              public Iterator<Entry<String, String>> answer() {
                return systemConfig.iterator();
              }
            })
        .anyTimes();

    replay(instance, factory, siteConfig);

    credentials = SystemCredentials.get(instance);
    gc = new SimpleGarbageCollector(opts, volMgr, factory);
  }
  protected final MetaDataLocator neverWhitelistProtected() {
    MetaDataLocator l = mockMetaDataLocator();

    expect(
            l.findMeta(
                EasyMock.anyObject(String.class),
                EasyMock.anyObject(String.class),
                EasyMock.eq(boolean.class)))
        .andReturn(false);

    return l;
  }
  @Before
  public void ignoreTiming() {
    mTiming = PowerMock.createMock(Timing.class);

    mTiming.lap((String) EasyMock.anyObject());
    EasyMock.expectLastCall().anyTimes();
  }
  @Test
  public void testPubsubWiring() throws Exception {
    expect(cronScheduler.startAsync()).andReturn(cronScheduler);
    cronScheduler.awaitRunning();
    shutdownRegistry.addAction(EasyMock.<ExceptionalCommand<?>>anyObject());
    expect(storageUtil.jobStore.fetchJobs(MANAGER_KEY))
        .andReturn(ImmutableList.<IJobConfiguration>of());

    control.replay();

    Injector injector =
        Guice.createInjector(
            new AbstractModule() {
              @Override
              protected void configure() {
                bind(StateManager.class).toInstance(stateManager);
                bind(Storage.class).toInstance(storageUtil.storage);
                bind(CronScheduler.class).toInstance(cronScheduler);
                bind(ShutdownRegistry.class).toInstance(shutdownRegistry);
                bind(SchedulerCore.class).toInstance(scheduler);
                PubsubTestUtil.installPubsub(binder());
                StateModule.bindCronJobManager(binder());
              }
            });
    cron = injector.getInstance(CronJobManager.class);
    EventSink eventSink = PubsubTestUtil.startPubsub(injector);
    eventSink.post(new SchedulerActive());
  }
  protected void setUp() throws Exception {
    super.setUp();

    ReflectionFactory reflectionFactory = EasyMock.createNiceMock(ReflectionFactory.class);
    LifecycleInvoker invoker = EasyMock.createMock(LifecycleInvoker.class);
    EasyMock.expect(reflectionFactory.createLifecycleInvoker(EasyMock.isA(Method.class)))
        .andReturn(invoker);

    ClassLoaderRegistry classLoaderRegistry = EasyMock.createMock(ClassLoaderRegistry.class);
    EasyMock.expect(classLoaderRegistry.getClassLoader(EasyMock.anyObject()))
        .andReturn(getClass().getClassLoader())
        .anyTimes();
    EasyMock.replay(reflectionFactory, classLoaderRegistry);

    builder = new ImplementationManagerFactoryBuilderImpl(reflectionFactory, classLoaderRegistry);
    Constructor<Foo> constructor = Foo.class.getConstructor(String.class, Long.class);

    definition = new ImplementationManagerDefinition();
    definition.setImplementationClass(Foo.class);
    definition.setConstructor(constructor);
    definition.setInitMethod(Foo.class.getMethod("init"));
    definition.setDestroyMethod(Foo.class.getMethod("destroy"));
    Map<InjectionSite, Injectable> construction = definition.getConstruction();
    construction.put(
        new ConstructorInjectionSite(constructor, 0), new Injectable(InjectableType.PROPERTY, "a"));
    construction.put(
        new ConstructorInjectionSite(constructor, 1),
        new Injectable(InjectableType.REFERENCE, "b"));
  }
  public void testRun() throws Exception {
    // Expect service data calls
    TripStatistics stats = new TripStatistics();

    // Expect announcement building call
    expect(mockTask.getAnnouncement(same(stats))).andStubReturn(ANNOUNCEMENT);

    // Put task in "ready" state
    startTask(TextToSpeech.SUCCESS);

    expect(tts.isLanguageAvailable(DEFAULT_LOCALE)).andStubReturn(TextToSpeech.LANG_AVAILABLE);
    expect(tts.setLanguage(DEFAULT_LOCALE)).andReturn(TextToSpeech.LANG_AVAILABLE);
    expect(tts.setSpeechRate(AnnouncementPeriodicTask.TTS_SPEECH_RATE))
        .andReturn(TextToSpeech.SUCCESS);
    expect(tts.setOnUtteranceCompletedListener((OnUtteranceCompletedListener) EasyMock.anyObject()))
        .andReturn(0);

    // Expect actual announcement call
    expect(
            tts.speak(
                eq(ANNOUNCEMENT),
                eq(TextToSpeech.QUEUE_FLUSH),
                eq(AnnouncementPeriodicTask.SPEECH_PARAMS)))
        .andReturn(0);

    // Run the announcement
    AndroidMock.replay(tts);
    task.announce(stats);
    AndroidMock.verify(mockTask, tts);
  }
  @Test
  public void testDeployProcess() throws PluginException {
    HashSet<RequestParameterType<?>> mandatoryProperties = new HashSet<>();
    RequestParameterType<String> prop = new RequestParameterType<>("test", "test");
    mandatoryProperties.add(prop);

    CanonicalProcessType cpf = new CanonicalProcessType();
    AnnotationsType anf = new AnnotationsType();

    expect(mockDeploymentPlugin.getNativeType()).andReturn("test");
    expect(mockDeploymentPlugin.getName()).andReturn("test");
    expect(mockDeploymentPlugin.getVersion()).andReturn("1.0");
    PluginResultImpl result = new PluginResultImpl();
    result.addPluginMessage("test");
    expect(
            mockDeploymentPlugin.deployProcess(
                EasyMock.eq(cpf), EasyMock.eq(anf), EasyMock.anyObject(PluginRequest.class)))
        .andReturn(result);

    replay(mockDeploymentPlugin);

    List<PluginMessage> messages = myService.deployProcess("test", cpf, anf, mandatoryProperties);
    assertTrue(messages.size() == 1);

    verify(mockDeploymentPlugin);
  }
  @Test
  public void testThrowExceptionIfReturnOriginalContentOnErrorNotSet() throws Exception {
    String url = "http://example.org/mypage.html";
    String domain = "example.org";

    setupProxyRequestMock(domain, url, true, -1, null, null);

    String contentType = "text/html; charset=UTF-8";
    HttpResponse resp =
        new HttpResponseBuilder()
            .setResponseString("Hello")
            .addHeader("Content-Type", contentType)
            .create();

    expect(pipeline.execute((HttpRequest) EasyMock.anyObject())).andReturn(resp);

    replay();

    final StringBuilder stringBuilder = new StringBuilder("");
    ResponseRewriter rewriter = getResponseRewriterThatThrowsExceptions(stringBuilder);

    ResponseRewriterRegistry rewriterRegistry =
        new DefaultResponseRewriterRegistry(Arrays.<ResponseRewriter>asList(rewriter), null);
    ProxyHandler proxyHandler = new ProxyHandler(pipeline, rewriterRegistry, true);

    boolean exceptionCaught = false;
    try {
      proxyHandler.fetch(request);
    } catch (GadgetException e) {
      exceptionCaught = true;
      assertEquals(404, e.getHttpStatusCode());
    }
    assertTrue(exceptionCaught);
    assertEquals("exceptionThrown", stringBuilder.toString());
  }
  private OpenStreetMapSimpleImporter createImporterThatThrows() {
    OpenStreetMapSimpleImporter importer =
        new OpenStreetMapSimpleImporter() {
          @Override
          public boolean shouldBeSkipped() {
            return false;
          }

          @Override
          public long getNumberOfLinesToProcess() {
            return 2L;
          }

          @Override
          protected void tearDown() {
            return;
          }
        };

    // ImporterConfig config = new ImporterConfig();
    // config.setOpenStreetMapDir(this.openStreetMapImporter.importerConfig.getOpenStreetMapDir());
    IOpenStreetMapDao dao = EasyMock.createNiceMock(IOpenStreetMapDao.class);
    // now we simulate the fact that the dao should not be called
    EasyMock.expect(dao.save((OpenStreetMap) EasyMock.anyObject()))
        .andThrow(new RuntimeException("message"));
    EasyMock.replay(dao);
    importer.setOpenStreetMapDao(dao);
    importer.setImporterConfig(new ImporterConfig());
    // importer.setTransactionManager(openStreetMapImporter.transactionManager);
    return importer;
  }
  @Test
  public void testReadConfig_JDBC() throws Exception {
    // 建立私有方法的mock对象
    ConfigParamManager mock =
        PowerMock.createPartialMock(ConfigParamManager.class, "getConfigType");
    // 录制私有方法行为
    PowerMock.expectPrivate(mock, "getConfigType", EasyMock.anyObject(Document.class))
        .andReturn("JDBC");
    // 回放mock对象行为
    PowerMock.replay(mock);

    EnvConfigBean envConfig = mock.readConfig(configLocation);

    assertNotNull(envConfig);
    assertEquals("JDBC", envConfig.getConfigType());
    assertTrue(envConfig.getJdbc().keySet().size() > 0);
    for (ConfigDataSourceBean csb : envConfig.getJdbc().values()) {
      System.out.println("jdbc config==>" + csb.getName() + " = " + csb.getValue());
    }
    for (ConfigParamBean cpb : ConfigParamMap.getConfigParamMap().values()) {
      System.out.println(
          "jdbc configParam==>"
              + cpb.getName()
              + " || "
              + cpb.getValue()
              + " || "
              + cpb.getSystem());
    }
  }
  // ProxyHandler throws INTERNAL_SERVER_ERRORS without isRecoverable() check.
  @Test
  public void testRecoverableRewritingException() throws Exception {
    String url = "http://example.org/mypage.html";
    String domain = "example.org";

    setupProxyRequestMock(domain, url, true, -1, null, null);

    String contentType = "text/html; charset=UTF-8";
    HttpResponse resp =
        new HttpResponseBuilder()
            .setResponseString("Hello")
            .addHeader("Content-Type", contentType)
            .create();

    expect(pipeline.execute((HttpRequest) EasyMock.anyObject())).andReturn(resp);

    replay();

    final StringBuilder stringBuilder = new StringBuilder("");
    ResponseRewriter rewriter = getResponseRewriterThatThrowsExceptions(stringBuilder);

    ResponseRewriterRegistry rewriterRegistry =
        new DefaultResponseRewriterRegistry(Arrays.<ResponseRewriter>asList(rewriter), null);
    ProxyHandler proxyHandler = new ProxyHandler(pipeline, rewriterRegistry, true);

    request.setReturnOriginalContentOnError(true);
    HttpResponse recorder = proxyHandler.fetch(request);

    verify();

    // Ensure that original content is returned.
    assertEquals(recorder.getHeader("Content-Type"), contentType);
    assertEquals("Hello", recorder.getResponseAsString());
    assertEquals("exceptionThrown", stringBuilder.toString());
  }
 @Test
 @SuppressWarnings("unchecked")
 public void getStringMemcacheTranscoderOfTLong() throws TimeoutException, CacheException {
   CacheTranscoder transcoder = EasyMock.createMock(CacheTranscoder.class);
   EasyMock.expect(client.asyncGet(EasyMock.eq("key1"), EasyMock.anyObject(Transcoder.class)))
       .andReturn(getFuture("test-value"));
   EasyMock.replay(client);
   assertEquals("test-value", clientWrapper.get("key1", transcoder, 100));
   EasyMock.verify(client);
 }
  @Test
  public void testSetIsInFields_GetByShape() {
    OpenStreetMapSimpleImporter openStreetMapSimpleImporter = new OpenStreetMapSimpleImporter();

    Point location = GeolocHelper.createPoint(2F, 3F);

    String countryCode = "FR";

    ICityDao cityDao = EasyMock.createMock(ICityDao.class);
    City cityByShape = new City();
    cityByShape.addZipCode(new ZipCode("zip"));
    cityByShape.setName("name");
    cityByShape.setPopulation(1000000);
    Adm adm = new Adm(2);
    adm.setName("admName");
    cityByShape.setAdm(adm);
    cityByShape.setFeatureId(1L);
    cityByShape.setId(123L);
    EasyMock.expect(
            cityDao.getByShape(
                EasyMock.anyObject(Point.class),
                EasyMock.anyObject(String.class),
                EasyMock.eq(true)))
        .andReturn(cityByShape);
    EasyMock.replay(cityDao);
    openStreetMapSimpleImporter.setCityDao(cityDao);

    OpenStreetMap street = new OpenStreetMap();
    street.setCountryCode(countryCode);
    street.setLocation(location);
    openStreetMapSimpleImporter.setIsInFields(street);

    Set<String> expectedZip = new HashSet<String>();
    expectedZip.add("ZIP");
    Assert.assertEquals(expectedZip, street.getIsInZip());
    Assert.assertEquals(true, street.isCityConfident());
    Assert.assertEquals("admName", street.getIsInAdm());
    Assert.assertEquals("name", street.getIsIn());
    Assert.assertEquals(123L, street.getCityId());
    Assert.assertEquals(null, street.getIsInPlace());

    EasyMock.verify(cityDao);
  }
  @Test(timeout = 4000L)
  public void testRealtimeIndexTask() throws Exception {
    monitorScheduler.addMonitor(EasyMock.anyObject(Monitor.class));
    EasyMock.expectLastCall().atLeastOnce();
    monitorScheduler.removeMonitor(EasyMock.anyObject(Monitor.class));
    EasyMock.expectLastCall().anyTimes();
    EasyMock.replay(monitorScheduler, queryRunnerFactoryConglomerate);

    RealtimeIndexTask realtimeIndexTask = giveMeARealtimeIndexTask();
    final String taskId = realtimeIndexTask.getId();

    tq.add(realtimeIndexTask);
    // wait for task to process events and publish segment
    Assert.assertTrue(publishCountDown.await(1000, TimeUnit.MILLISECONDS));

    // Realtime Task has published the segment, simulate loading of segment to a historical node so
    // that task finishes with SUCCESS status
    segmentCallbacks
        .get(0)
        .segmentAdded(
            new DruidServerMetadata("dummy", "dummy_host", 0, "historical", "dummy_tier", 0),
            mdc.getPublished().iterator().next());

    // Wait for realtime index task to handle callback in plumber and succeed
    while (tsqa.getStatus(taskId).get().isRunnable()) {
      Thread.sleep(10);
    }

    Assert.assertTrue("Task should be in Success state", tsqa.getStatus(taskId).get().isSuccess());

    Assert.assertEquals(1, announcedSinks);
    Assert.assertEquals(1, pushedSegments);
    Assert.assertEquals(1, mdc.getPublished().size());
    DataSegment segment = mdc.getPublished().iterator().next();
    Assert.assertEquals("test_ds", segment.getDataSource());
    Assert.assertEquals(ImmutableList.of("dim1", "dim2"), segment.getDimensions());
    Assert.assertEquals(
        new Interval(now.toString("YYYY-MM-dd") + "/" + now.plusDays(1).toString("YYYY-MM-dd")),
        segment.getInterval());
    Assert.assertEquals(ImmutableList.of("count"), segment.getMetrics());
    EasyMock.verify(monitorScheduler, queryRunnerFactoryConglomerate);
  }
Exemple #21
0
  /**
   * Set up
   *
   * @throws java.lang.Exception
   */
  @Before
  public void setUp() throws Exception {
    car = new Car();

    roadMapMock = EasyMock.createMock(IRoadMap.class);
    EasyMock.expect(roadMapMock.indicateBarrier((Position) EasyMock.anyObject()))
        .andReturn(false)
        .anyTimes();
    car.getGps().setRoadMap(roadMapMock);
    EasyMock.replay(roadMapMock);
  }
  @Test
  public void testGetOspfLinkStatusDown() {
    EasyMock.expect(
            m_alarmDao.findMatching(EasyMock.anyObject(org.opennms.core.criteria.Criteria.class)))
        .andReturn(createDownAlarm());
    EasyMock.expect(
            m_ospfLinkDao.findMatching(EasyMock.<org.opennms.core.criteria.Criteria>anyObject()))
        .andReturn(createOspfLinks());

    EasyMock.replay(m_alarmDao, m_ospfLinkDao);

    List<EdgeRef> edges = createEdges();
    Map<EdgeRef, Status> statusMap =
        m_statusProvider.getStatusForEdges(m_edgeProvider, edges, new Criteria[0]);

    assertEquals(1, statusMap.size());
    assertEquals(edges.get(0), new ArrayList<EdgeRef>(statusMap.keySet()).get(0));
    Status status = statusMap.get(edges.get(0));
    assertEquals("down", status.computeStatus());
  }
  @Test(expected = ScheduleException.class)
  public void testScheduleFails() throws Exception {
    expectJobValidated(job);
    storageUtil.jobStore.saveAcceptedJob(MANAGER_KEY, sanitizedConfiguration.getJobConfig());
    expect(cronScheduler.schedule(eq(job.getCronSchedule()), EasyMock.<Runnable>anyObject()))
        .andThrow(new CronException("injected"));

    control.replay();

    cron.receiveJob(sanitizedConfiguration);
  }
  @Test
  public void testRunOverlapLoadedSuccessfully() throws Exception {
    // Existing RUN_OVERLAP jobs should still load and map.

    expect(cronScheduler.startAsync()).andReturn(cronScheduler);
    cronScheduler.awaitRunning();
    shutdownRegistry.addAction(EasyMock.<ExceptionalCommand<?>>anyObject());

    IJobConfiguration jobA =
        IJobConfiguration.build(
            makeJob().newBuilder().setCronCollisionPolicy(CronCollisionPolicy.RUN_OVERLAP));

    expect(storageUtil.jobStore.fetchJobs(MANAGER_KEY)).andReturn(ImmutableList.of(jobA));
    expect(cronScheduler.isValidSchedule(jobA.getCronSchedule())).andReturn(true);
    expect(cronScheduler.schedule(eq(jobA.getCronSchedule()), EasyMock.<Runnable>anyObject()))
        .andReturn("keyA");

    control.replay();

    cron.schedulerActive(new SchedulerActive());
  }
  @Test
  public void testSetIsInFields_both_null() {
    OpenStreetMapSimpleImporter openStreetMapSimpleImporter = new OpenStreetMapSimpleImporter();

    final City city = new City();
    city.setMunicipality(false);
    final List<ZipCode> zipCodes = new ArrayList<ZipCode>();
    zipCodes.add(new ZipCode("zip1"));
    Point location = GeolocHelper.createPoint(2F, 3F);

    String countryCode = "FR";

    ICityDao cityDao = EasyMock.createMock(ICityDao.class);
    EasyMock.expect(
            cityDao.getByShape(
                EasyMock.anyObject(Point.class),
                EasyMock.anyObject(String.class),
                EasyMock.eq(true)))
        .andReturn(null);
    EasyMock.expect(
            cityDao.getNearest(location, countryCode, true, OpenStreetMapSimpleImporter.DISTANCE))
        .andReturn(city);
    EasyMock.expect(
            cityDao.getNearest(location, countryCode, false, OpenStreetMapSimpleImporter.DISTANCE))
        .andReturn(null);
    EasyMock.replay(cityDao);
    openStreetMapSimpleImporter.setCityDao(cityDao);

    OpenStreetMap street = new OpenStreetMap();
    street.setCountryCode(countryCode);
    street.setLocation(location);
    openStreetMapSimpleImporter.setIsInFields(street);

    Assert.assertEquals(null, street.getIsInZip());
    Assert.assertEquals(null, street.getIsInAdm());
    Assert.assertEquals(null, street.getIsIn());
    Assert.assertEquals(null, street.getIsInPlace());

    EasyMock.verify(cityDao);
  }
Exemple #26
0
  private RepositoryAdminImpl createRepositoryAdmin() throws Exception {
    BundleContext bundleContext = (BundleContext) EasyMock.createMock(BundleContext.class);
    Bundle systemBundle = (Bundle) EasyMock.createMock(Bundle.class);

    Activator.setContext(bundleContext);
    EasyMock.expect(bundleContext.getProperty(RepositoryAdminImpl.REPOSITORY_URL_PROP))
        .andReturn(getClass().getResource("/referred.xml").toExternalForm());
    EasyMock.expect(bundleContext.getProperty((String) EasyMock.anyObject()))
        .andReturn(null)
        .anyTimes();
    EasyMock.expect(bundleContext.getBundle(0)).andReturn(systemBundle);
    EasyMock.expect(systemBundle.getHeaders()).andReturn(new Hashtable());
    EasyMock.expect(systemBundle.getRegisteredServices()).andReturn(null);
    EasyMock.expect(new Long(systemBundle.getBundleId())).andReturn(new Long(0)).anyTimes();
    EasyMock.expect(systemBundle.getBundleContext()).andReturn(bundleContext);
    bundleContext.addBundleListener((BundleListener) EasyMock.anyObject());
    bundleContext.addServiceListener((ServiceListener) EasyMock.anyObject());
    EasyMock.expect(bundleContext.getBundles()).andReturn(new Bundle[] {systemBundle});
    final Capture c = new Capture();
    EasyMock.expect(bundleContext.createFilter((String) capture(c)))
        .andAnswer(
            new IAnswer() {
              public Object answer() throws Throwable {
                return FilterImpl.newInstance((String) c.getValue());
              }
            })
        .anyTimes();
    EasyMock.replay(new Object[] {bundleContext, systemBundle});

    RepositoryAdminImpl repoAdmin =
        new RepositoryAdminImpl(bundleContext, new Logger(bundleContext));

    // force initialization && remove all initial repositories
    Repository[] repos = repoAdmin.listRepositories();
    for (int i = 0; repos != null && i < repos.length; i++) {
      repoAdmin.removeRepository(repos[i].getURI());
    }

    return repoAdmin;
  }
 private ImmutableZkWorker createMockWorker(
     int currCapacityUsed, boolean canRunTask, boolean isValidVersion) {
   ImmutableZkWorker worker = EasyMock.createMock(ImmutableZkWorker.class);
   EasyMock.expect(worker.canRunTask(EasyMock.anyObject(Task.class)))
       .andReturn(canRunTask)
       .anyTimes();
   EasyMock.expect(worker.getCurrCapacityUsed()).andReturn(currCapacityUsed).anyTimes();
   EasyMock.expect(worker.isValidVersion(EasyMock.anyString()))
       .andReturn(isValidVersion)
       .anyTimes();
   EasyMock.replay(worker);
   return worker;
 }
Exemple #28
0
  /**
   * Confirms that the expandToDirectory()-method calls the proper expand methods for known archive
   * types.
   *
   * @throws Exception
   */
  public void testExpandToDirectory() throws Exception {
    String filePath = "/foo/bar.tar";
    File file = new File(filePath);

    expect(fileSystem.getTemporaryDirectory(EasyMock.<String>anyObject()))
        .andReturn(new File("/test"));
    fileSystem.makeDirs(EasyMock.<File>anyObject());
    EasyMock.expectLastCall().once();
    expect(
            mockcmd.runCommand(
                EasyMock.<String>anyObject(),
                EasyMock.<List<String>>anyObject(),
                EasyMock.<String>anyObject()))
        .andReturn(null);
    control.replay();
    // Run the .expandToDirectory method.
    File directory = Utils.expandToDirectory(file);
    assertNotNull(directory);
    assertEquals("/test", directory.toString());

    control.verify();
  }
  @Test(expected = IllegalStateException.class)
  public void testJobStoredTwice() throws Exception {
    // Simulate an inconsistent storage that contains two cron jobs under the same key.

    expect(cronScheduler.startAsync()).andReturn(cronScheduler);
    cronScheduler.awaitRunning();
    shutdownRegistry.addAction(EasyMock.<ExceptionalCommand<?>>anyObject());

    IJobConfiguration jobA =
        IJobConfiguration.build(makeJob().newBuilder().setCronSchedule("1 2 3 4 5"));
    IJobConfiguration jobB =
        IJobConfiguration.build(makeJob().newBuilder().setCronSchedule("* * * * *"));
    expect(storageUtil.jobStore.fetchJobs(MANAGER_KEY)).andReturn(ImmutableList.of(jobA, jobB));
    expectJobValidated(jobA);
    expect(cronScheduler.schedule(eq(jobA.getCronSchedule()), EasyMock.<Runnable>anyObject()))
        .andReturn("keyA");
    expectJobValidated(jobB);

    control.replay();

    cron.schedulerActive(new SchedulerActive());
  }
  @Test(expectedExceptions = IllegalStateException.class)
  void registerMBeanFailed()
      throws NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanException,
          MalformedObjectNameException, AttributeNotFoundException, ReflectionException,
          InstanceNotFoundException {
    MBeanServer server = EasyMock.createMock(MBeanServer.class);
    ObjectName oName = new ObjectName(JolokiaMBeanServerHolderMBean.OBJECT_NAME);
    EasyMock.expect(server.registerMBean(EasyMock.anyObject(), EasyMock.eq(oName)))
        .andThrow(new MBeanRegistrationException(new Exception()));
    EasyMock.replay(server);

    MBeanServer m = JolokiaMBeanServerUtil.registerJolokiaMBeanServerHolderMBean(server);
  }