/**
   * Get a list of "other" vms, along with stop modes. The "other" vms are any vms other than the
   * currently executing vm. The stop mode for each VM is chosen from util.StopStartPrms.stopMode.
   *
   * @param numVMsToTarget The number of VMs to target for a stop/start.
   * @param clientMatchStr A string the must be contained in the client name to be included in the
   *     vms to target, or null.
   * @throws TestException if there aren't numToTarget VMs available.
   * @returns Object[0] - a List of ClientVmInfos. Object[1] - a List of stop modes. Object[2] - a
   *     List of vms eligible but not chosen.
   */
  public static Object[] getOtherVMs(int numToTarget, String clientMatchStr) {
    Log.getLogWriter().info("Choosing " + numToTarget + " vms (other than this one)");
    // get the VMs; vmList and stopModeList are parallel lists
    ArrayList vmList = new ArrayList();
    ArrayList stopModeList = new ArrayList();
    int myVmID = RemoteTestModule.getMyVmid();

    // get VMs that contain the clientMatchStr
    List vmInfoList = getAllVMs();
    vmInfoList = getMatchVMs(vmInfoList, clientMatchStr);

    // now all vms in vmInfoList match the clientMatchStr
    do {
      if (vmInfoList.size() == 0) {
        throw new TestException(
            "Unable to find "
                + numToTarget
                + " vms to stop with client match string "
                + clientMatchStr
                + "; either a test problem or add StopStartVMs.StopStart_initTask to the test");
      }
      // add a VmId to the list of vms to stop
      int randInt = TestConfig.tab().getRandGen().nextInt(0, vmInfoList.size() - 1);
      ClientVmInfo info = (ClientVmInfo) (vmInfoList.get(randInt));
      if (info.getVmid().intValue() != myVmID) { // info is not the current VM
        vmList.add(info);

        // choose a stopMode
        String choice = TestConfig.tab().stringAt(StopStartPrms.stopModes);
        stopModeList.add(choice);
      }
      vmInfoList.remove(randInt);
    } while (vmList.size() < numToTarget);
    return new Object[] {vmList, stopModeList, vmInfoList};
  }
  @Test
  @Category(IntegrationTest.class)
  public void developerEditionAppUserWorks() {
    final String enterpriseId = TestConfig.getEnterpriseID();
    final String clientId = TestConfig.getClientID();
    final String clientSecret = TestConfig.getClientSecret();
    final String privateKey = TestConfig.getPrivateKey();
    final String privateKeyPassword = TestConfig.getPrivateKeyPassword();

    BoxDeveloperEditionConnection appAuthConnection =
        BoxDeveloperEditionConnection.getAppAuthConnection(
            enterpriseId, clientId, clientSecret, privateKey, privateKeyPassword);
    final String name = "app user name two";
    BoxUser.Info createdUserInfo = BoxUser.createAppUser(appAuthConnection, name);
    final String appUserId = createdUserInfo.getID();

    BoxDeveloperEditionConnection api =
        BoxDeveloperEditionConnection.getAppUserConnection(
            appUserId, clientId, clientSecret, privateKey, privateKeyPassword);
    BoxUser appUser = new BoxUser(api, appUserId);

    assertThat(api.getAccessToken(), not(equalTo(null)));

    BoxUser.Info info = appUser.getInfo();

    assertThat(info.getID(), equalTo(appUserId));
    assertThat(info.getName(), equalTo(name));

    api.refresh();

    BoxUser appUserFromAdmin = new BoxUser(appAuthConnection, appUserId);
    appUserFromAdmin.delete(false, true);
  }
  @Test
  public void testDuelESLucene() throws Exception {
    AbstractTermVectorTests.TestFieldSetting[] testFieldSettings = getFieldSettings();
    createIndexBasedOnFieldSettings(testFieldSettings, -1);
    AbstractTermVectorTests.TestDoc[] testDocs = generateTestDocs(5, testFieldSettings);

    DirectoryReader directoryReader = indexDocsWithLucene(testDocs);
    AbstractTermVectorTests.TestConfig[] testConfigs =
        generateTestConfigs(20, testDocs, testFieldSettings);

    MultiTermVectorsRequestBuilder requestBuilder = client().prepareMultiTermVectors();
    for (AbstractTermVectorTests.TestConfig test : testConfigs) {
      requestBuilder.add(getRequestForConfig(test).request());
    }

    MultiTermVectorsItemResponse[] responseItems = requestBuilder.get().getResponses();

    for (int i = 0; i < testConfigs.length; i++) {
      TestConfig test = testConfigs[i];
      try {
        MultiTermVectorsItemResponse item = responseItems[i];
        if (test.expectedException != null) {
          assertTrue(item.isFailed());
          continue;
        } else if (item.isFailed()) {
          fail(item.getFailure().getMessage());
        }
        Fields luceneTermVectors = getTermVectorsFromLucene(directoryReader, test.doc);
        validateResponse(item.getResponse(), luceneTermVectors, test);
      } catch (Throwable t) {
        throw new Exception("Test exception while running " + test.toString(), t);
      }
    }
  }
Example #4
0
 private boolean callgeo(TestConfig conf) throws Exception {
   // logger.debug(conf.toString());
   ByteBuffer wa1 = ByteBuffer.wrap(conf.getInput().getBytes());
   ByteBuffer wa2 = ByteBuffer.allocate(conf.getLengthOfWorkAreaTwo());
   geoclient.callgeo(wa1, wa2);
   String wa1Result = decode(wa1);
   String wa2Result = decode(wa2);
   String rc = getReturnCode(wa1Result);
   String message =
       String.format(
           "Result of %s call:  geosupportReturnCode = \"%s\"", conf.getFunctionName(), rc);
   boolean isSuccess = isSuccess(rc);
   String wa1Msg = String.format("WA1 of %s:", conf.getFunctionName());
   String wa2Msg = String.format("WA2 of %s:", conf.getFunctionName());
   if (isSuccess) {
     logger.debug(message);
     logger.debug(wa1Msg);
     logger.raw(Logger.LEVEL_DEBUG, wa1Result);
     logger.debug(wa2Msg);
     logger.raw(Logger.LEVEL_DEBUG, wa2Result);
   } else {
     logger.error(message);
     logger.error(wa1Msg);
     logger.raw(Logger.LEVEL_ERROR, wa1Result);
     logger.error(wa2Msg);
     logger.raw(Logger.LEVEL_ERROR, wa2Result);
   }
   return isSuccess;
 }
  @Test
  public void testConfigCmds() {
    // This is for basic testing for the config APIs. DR mode specific tests are implemented
    // separately.
    if (TestConfig.getInstance().getClientMode() == ClientMode.Dynamic) {
      return;
    }

    final String config = "1\nlocalhost|127.0.0.1|11211";
    client.getVersions();
    Collection<NodeEndPoint> endpoints = client.getAvailableNodeEndPoints();
    InetSocketAddress sa = endpoints.iterator().next().getInetSocketAddress();
    if (TestConfig.getInstance().getEngineType().isSetConfigSupported()) {
      client.deleteConfig(sa, ConfigurationType.CLUSTER);
      assertNull(client.getConfig(sa, ConfigurationType.CLUSTER));
      client.setConfig(sa, ConfigurationType.CLUSTER, config);
      String configFromServer = (String) client.getConfig(sa, ConfigurationType.CLUSTER);
      assertEquals(config, configFromServer);
      client.deleteConfig(sa, ConfigurationType.CLUSTER);
      assertNull(client.getConfig(sa, ConfigurationType.CLUSTER));
    } else {
      String configKey = ConfigurationType.CLUSTER.getValueWithNameSpace();
      client.delete(configKey);
      assertNull(client.get(configKey));
      client.set(configKey, 0, config);
      String configFromServer = (String) client.get(configKey);
      assertEquals(config, configFromServer);
      client.delete(configKey);
      assertNull(client.get(configKey));
    }
  }
  @Override
  protected void initClient(ConnectionFactory cf) throws Exception {
    if (TestConfig.getInstance().getClientMode() == ClientMode.Dynamic) {
      List<InetSocketAddress> addrs = AddrUtil.getAddresses(TestConfig.IPV4_ADDR + ":11212");
      MemcachedClient staticClient = new MemcachedClient(addrs);

      if (TestConfig.getInstance().getEngineType().isSetConfigSupported()) {
        staticClient.setConfig(
            addrs.get(0),
            ConfigurationType.CLUSTER,
            "1\n" + "localhost.localdomain|" + TestConfig.IPV4_ADDR + "|" + "11212");
        client = new MemcachedClient(cf, AddrUtil.getAddresses(TestConfig.IPV4_ADDR + ":11212"));
        staticClient.setConfig(
            addrs.get(0),
            ConfigurationType.CLUSTER,
            "2\nlocalhost.localdomain|" + TestConfig.IPV4_ADDR + "|64213");
      } else {
        staticClient.set(
            ConfigurationType.CLUSTER.getValueWithNameSpace(),
            0,
            "1\n" + "localhost.localdomain|" + TestConfig.IPV4_ADDR + "|" + "11212");
        client = new MemcachedClient(cf, AddrUtil.getAddresses(TestConfig.IPV4_ADDR + ":11212"));
        staticClient.set(
            ConfigurationType.CLUSTER.getValueWithNameSpace(),
            0,
            "2\nlocalhost.localdomain|" + TestConfig.IPV4_ADDR + "|64213");
      }
      // Add a delay to allow time for dynamic mode client to pickup the config.
      Thread.sleep(10000);
    } else {
      client = new MemcachedClient(cf, AddrUtil.getAddresses(TestConfig.IPV4_ADDR + ":64213"));
    }
  }
 @Test
 public void testDelayedFlush() throws Exception {
   String current_config = null;
   Collection<NodeEndPoint> endpoints = new ArrayList<NodeEndPoint>();
   if (TestConfig.getInstance().getClientMode().equals(ClientMode.Dynamic)
       && !TestConfig.getInstance().getEngineType().isSetConfigSupported()) {
     current_config = getCurrentConfigAndClusterEndpoints(client, endpoints);
   }
   assertNull(client.get("test1"));
   assert client.set("test1", 5, "test1value").getStatus().isSuccess();
   assert client.set("test2", 5, "test2value").getStatus().isSuccess();
   assertEquals("test1value", client.get("test1"));
   assertEquals("test2value", client.get("test2"));
   assert client.flush(2).getStatus().isSuccess();
   Thread.sleep(2100);
   if (TestConfig.getInstance().getClientMode().equals(ClientMode.Dynamic)
       && !TestConfig.getInstance().getEngineType().isSetConfigSupported()) {
     Thread.sleep(1000);
     restoreClusterConfig(current_config, endpoints);
     Thread.sleep(1000); // Wait for the config to restore
   }
   assertNull(client.get("test1"));
   assertNull(client.get("test2"));
   assert !client.asyncGet("test1").getStatus().isSuccess();
   assert !client.asyncGet("test2").getStatus().isSuccess();
 }
 @Test
 public void testDelayedflushCancellation() throws Exception {
   String current_config = null;
   Collection<NodeEndPoint> endpoints = new ArrayList<NodeEndPoint>();
   if (TestConfig.getInstance().getClientMode().equals(ClientMode.Dynamic)
       && !TestConfig.getInstance().getEngineType().isSetConfigSupported()) {
     current_config = getCurrentConfigAndClusterEndpoints(client, endpoints);
   }
   tryTestSequence(client.flush(3));
   if (TestConfig.getInstance().getClientMode().equals(ClientMode.Dynamic)
       && !TestConfig.getInstance().getEngineType().isSetConfigSupported()) {
     restoreClusterConfig(current_config, endpoints);
   }
 }
 /**
  * Get a random operation to perform. The set of operations available are in the BitSet. These
  * bits correspond to the operations defined in this class.
  *
  * @param bs True bits correspond to operations available to be chosen.
  * @param bsSize The number of bits to consider.
  * @return An operation as defined in this class.
  */
 protected int getOp(BitSet bs, int bsSize) {
   int randInt;
   do {
     randInt = TestConfig.tab().getRandGen().nextInt(1, bsSize);
   } while (!bs.get(randInt));
   return randInt;
 }
Example #10
0
  @Test
  @Category(IntegrationTest.class)
  public void downloadFileRangeSucceeds() throws IOException {
    BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken());
    BoxFolder rootFolder = BoxFolder.getRootFolder(api);
    String fileName = "Tamme-Lauri_tamm_suvepäeval.jpg";
    URL fileURL = this.getClass().getResource("/sample-files/" + fileName);
    String filePath = URLDecoder.decode(fileURL.getFile(), "utf-8");
    long fileSize = new File(filePath).length();
    byte[] fileContent = readAllBytes(filePath);

    InputStream uploadStream = new FileInputStream(filePath);
    ProgressListener mockUploadListener = mock(ProgressListener.class);
    BoxFile.Info uploadedFileInfo =
        rootFolder.uploadFile(uploadStream, fileName, fileSize, mockUploadListener);
    BoxFile uploadedFile = uploadedFileInfo.getResource();
    long firstHalf = uploadedFileInfo.getSize() / 2;

    ByteArrayOutputStream downloadStream = new ByteArrayOutputStream();
    uploadedFile.downloadRange(downloadStream, 0, firstHalf);
    uploadedFile.downloadRange(downloadStream, firstHalf + 1);
    byte[] downloadedFileContent = downloadStream.toByteArray();

    assertThat(downloadedFileContent, is(equalTo(fileContent)));
    assertThat(
        rootFolder,
        hasItem(Matchers.<BoxItem.Info>hasProperty("ID", equalTo(uploadedFile.getID()))));
    verify(mockUploadListener, atLeastOnce())
        .onProgressChanged(anyLong(), longThat(is(equalTo(fileSize))));

    uploadedFile.delete();
  }
Example #11
0
  @Test
  @Category(IntegrationTest.class)
  public void createAndUpdateSharedLinkSucceeds() {
    BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken());
    BoxFolder rootFolder = BoxFolder.getRootFolder(api);
    String fileName = "[createAndUpdateSharedLinkSucceeds] Test File.txt";
    byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8);

    InputStream uploadStream = new ByteArrayInputStream(fileBytes);
    BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource();
    BoxSharedLink.Permissions permissions = new BoxSharedLink.Permissions();
    permissions.setCanDownload(true);
    permissions.setCanPreview(true);
    BoxSharedLink sharedLink =
        uploadedFile.createSharedLink(BoxSharedLink.Access.OPEN, null, permissions);

    assertThat(sharedLink.getURL(), not(isEmptyOrNullString()));

    sharedLink.getPermissions().setCanDownload(false);
    BoxFile.Info info = uploadedFile.new Info();
    info.setSharedLink(sharedLink);
    uploadedFile.updateInfo(info);

    assertThat(info.getSharedLink().getPermissions().getCanDownload(), is(false));

    uploadedFile.delete();
  }
Example #12
0
  @Test
  @Category(IntegrationTest.class)
  public void promoteVersionsSucceeds() throws UnsupportedEncodingException {
    BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken());
    BoxFolder rootFolder = BoxFolder.getRootFolder(api);
    String fileName = "[promoteVersionsSucceeds] Multi-version File.txt";
    String version1Content = "Version 1";
    byte[] version1Bytes = version1Content.getBytes(StandardCharsets.UTF_8);
    byte[] version2Bytes = "Version 2".getBytes(StandardCharsets.UTF_8);

    InputStream uploadStream = new ByteArrayInputStream(version1Bytes);
    BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource();
    uploadStream = new ByteArrayInputStream(version2Bytes);
    uploadedFile.uploadVersion(uploadStream);

    Collection<BoxFileVersion> versions = uploadedFile.getVersions();
    BoxFileVersion previousVersion = versions.iterator().next();
    previousVersion.promote();

    ByteArrayOutputStream downloadStream = new ByteArrayOutputStream();
    uploadedFile.download(downloadStream);
    String downloadedContent = downloadStream.toString(StandardCharsets.UTF_8.name());
    assertThat(downloadedContent, equalTo(version1Content));

    uploadedFile.delete();
  }
Example #13
0
  @Test
  @Category(IntegrationTest.class)
  public void shouldReturnTrashedAtForADeleteVersion() {
    BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken());
    BoxFolder rootFolder = BoxFolder.getRootFolder(api);
    String fileName = "[deleteVersionSucceeds] Multi-version File.txt";
    byte[] version1Bytes = "Version 1".getBytes(StandardCharsets.UTF_8);
    byte[] version2Bytes = "Version 2".getBytes(StandardCharsets.UTF_8);

    InputStream uploadStream = new ByteArrayInputStream(version1Bytes);
    BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource();
    uploadStream = new ByteArrayInputStream(version2Bytes);
    uploadedFile.uploadVersion(uploadStream);

    Collection<BoxFileVersion> versions = uploadedFile.getVersions();
    BoxFileVersion previousVersion = versions.iterator().next();

    assertThat(previousVersion.getTrashedAt(), is(nullValue()));

    previousVersion.delete();
    versions = uploadedFile.getVersions();
    previousVersion = versions.iterator().next();

    assertThat(previousVersion.getTrashedAt(), is(notNullValue()));

    uploadedFile.delete();
  }
Example #14
0
  @Test
  @Category(IntegrationTest.class)
  public void fileLockAndUnlockSucceeds() {
    BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken());
    BoxFolder rootFolder = BoxFolder.getRootFolder(api);
    String fileName = "[getInfoWithOnlyTheLockField] Test File.txt";
    String fileContent = "Test file";
    byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8);

    InputStream uploadStream = new ByteArrayInputStream(fileBytes);
    BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource();

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR, 1);
    Date expiresAt = calendar.getTime();
    uploadedFile.lock(expiresAt, false);

    BoxFile.Info uploadedFileInfo = uploadedFile.getInfo("lock", "created_by");
    BoxLock fileLock = uploadedFileInfo.getLock();

    assertThat(fileLock, is(instanceOf(BoxLock.class)));
    assertThat(fileLock.getExpiresAt().toString(), is(equalTo(expiresAt.toString())));
    assertThat(fileLock.getIsDownloadPrevented(), is(equalTo(false)));
    assertThat(
        fileLock.getCreatedBy().getID(), is(equalTo(uploadedFileInfo.getCreatedBy().getID())));

    uploadedFile.unlock();

    BoxFile.Info updatedFileInfo = uploadedFile.getInfo("lock");
    assertThat(updatedFileInfo.getLock(), is(nullValue()));

    updatedFileInfo.getResource().delete();
  }
  @Test
  public void testRuntimeBatchConfigurer() throws Exception {

    jobRepository.toString(); // needed to trigger lazy bean initialization

    assertSame(getTargetObject(jobRepository, JobRepository.class), testConfig.getCustomJobRepo());
  }
  /**
   * Hydra start task to initialize key intervals, which are ranges of keys which are to have an
   * operation done on them (invalidate, destroy, etc)
   */
  public static synchronized void StartTask_initialize() {
    int numKeys = TestConfig.tab().intAt(CQUtilPrms.numKeys);
    KeyIntervals intervals =
        new KeyIntervals(
            new int[] {
              KeyIntervals.NONE, KeyIntervals.INVALIDATE,
              KeyIntervals.DESTROY, KeyIntervals.UPDATE_EXISTING_KEY,
              KeyIntervals.GET
            },
            numKeys);
    CQUtilBB.getBB().getSharedMap().put(CQUtilBB.KeyIntervals, intervals);
    Log.getLogWriter().info("Created keyIntervals: " + intervals);

    // Set the counters for the next keys to use for each operation
    hydra.blackboard.SharedCounters sc = CQUtilBB.getBB().getSharedCounters();
    sc.setIfLarger(CQUtilBB.LASTKEY_INVALIDATE, intervals.getFirstKey(KeyIntervals.INVALIDATE) - 1);
    sc.setIfLarger(
        CQUtilBB.LASTKEY_LOCAL_INVALIDATE,
        intervals.getFirstKey(KeyIntervals.LOCAL_INVALIDATE) - 1);
    sc.setIfLarger(CQUtilBB.LASTKEY_DESTROY, intervals.getFirstKey(KeyIntervals.DESTROY) - 1);
    sc.setIfLarger(
        CQUtilBB.LASTKEY_LOCAL_DESTROY, intervals.getFirstKey(KeyIntervals.LOCAL_DESTROY) - 1);
    sc.setIfLarger(
        CQUtilBB.LASTKEY_UPDATE_EXISTING_KEY,
        intervals.getFirstKey(KeyIntervals.UPDATE_EXISTING_KEY) - 1);
    sc.setIfLarger(CQUtilBB.LASTKEY_GET, intervals.getFirstKey(KeyIntervals.GET) - 1);

    // show the blackboard
    CQUtilBB.getBB().printSharedMap();
    CQUtilBB.getBB().printSharedCounters();
  }
 /**
  * Get a random key from the given region that is within this instance's range. If no keys qualify
  * in the region, return null.
  *
  * @param aRegion - The region to get the key from.
  * @param excludeKey - The region to get the key from.
  * @returns A key from aRegion, or null.
  */
 public Object getRandomKey(Region aRegion, Object excludeKey) {
   long start = System.currentTimeMillis();
   int lower = ((Integer) (lowerKeyRange.get())).intValue();
   int upper = ((Integer) (upperKeyRange.get())).intValue();
   long randomKeyIndex = TestConfig.tab().getRandGen().nextLong(lower, upper);
   long startKeyIndex = randomKeyIndex;
   Object key = NameFactory.getObjectNameForCounter(randomKeyIndex);
   do {
     boolean done = false;
     if ((!(key.equals(excludeKey))) && (aRegion.containsKey(key))) done = true;
     if (done) break;
     randomKeyIndex++; // go to the next key
     if (randomKeyIndex > upper) randomKeyIndex = lower;
     if (randomKeyIndex == startKeyIndex) { // considered all keys
       key = null;
       break;
     }
     key = NameFactory.getObjectNameForCounter(randomKeyIndex);
   } while (true);
   long end = System.currentTimeMillis();
   Log.getLogWriter()
       .info(
           "Done in TxUtilKeyRange:getRandomKey, key is "
               + key
               + " "
               + aRegion.getFullPath()
               + " getRandomKey took "
               + (end - start)
               + " millis");
   return key;
 }
Example #18
0
  public void setUp() throws Exception {
    log.info("BEGIN " + getTestName()); // marker for log4j traces

    TestConfig tc = getTestConfig();
    if (tc == null) {
      log.warn("NO CONFIGURATION");
      ContextManager.getInstance().clearContext();
    } else {
      Class<?> contextClass = tc.getContextClass();
      if (!Context.class.isAssignableFrom(contextClass))
        throw new IllegalArgumentException(
            "contextClass(" + contextClass.getName() + ") must implements Context");

      // create a new context from the test config
      // and apply it
      ContextManager.getInstance().setContext(contextClass, tc, this);
    }
  }
Example #19
0
  /**
   * Initialize the bb This saves caching attributes in the blackboard that must only be read once
   * per test run.
   */
  public void initialize() {
    hydra.blackboard.SharedMap aMap = this.getSharedMap();

    // set hydra params in map which should only be read once
    String scope = TestConfig.tab().stringAt(CachePrms.scopeAttribute, null);
    String mirror = TestConfig.tab().stringAt(CachePrms.mirrorAttribute, null);
    String dataPolicy = TestConfig.tab().stringAt(CachePrms.dataPolicyAttribute, null);
    if (scope != null) {
      aMap.put(SCOPE, TestConfig.tab().stringAt(CachePrms.scopeAttribute, null));
      Log.getLogWriter().info("Scope attribute is " + aMap.get(SCOPE));
    }
    if (mirror != null) {
      aMap.put(MIRROR, TestConfig.tab().stringAt(CachePrms.mirrorAttribute, null));
      Log.getLogWriter().info("Mirroring attribute is " + aMap.get(MIRROR));
    }
    if (dataPolicy != null) {
      aMap.put(DATA_POLICY, dataPolicy);
      Log.getLogWriter().info("DataPolicy attribute is " + aMap.get(DATA_POLICY));
    }
  }
 /**
  * Return a List of all other vms except for one along with a parallel stop mode list, and also
  * return the one vm not in the list.
  *
  * @return [0] (List<ClientVmInfo>)A List of ClientVmInfo instances; this includes all vms except
  *     the current vm and except for one other vm. [1] (List<String>) A parallel List to [0]
  *     containing stop modes. [2] (ClientVMInfo) The ClientVmInfo instance of the one vm excluded
  *     from [0] (other than this vm) [3] (String) The stop mode for [2] [4] (List<ClientVmInfo>) A
  *     List of ClientVmInfo instances for all vms except this one. [5] (List<String>) A parallel
  *     List to [4] of stop modes.
  */
 public static Object[] getOtherVMsDivided(String[] excludedClientNames) {
   Vector<Integer> otherVmIDs = ClientVmMgr.getOtherClientVmids();
   List<ClientVmInfo> allOtherVMs = new ArrayList();
   List<String> stopModeList = new ArrayList();
   for (int i = 0; i < otherVmIDs.size(); i++) {
     ClientVmInfo info = new ClientVmInfo(otherVmIDs.get(i));
     ClientVmInfo infoFromBB =
         (ClientVmInfo) StopStartBB.getBB().getSharedMap().get(VmInfoKey + otherVmIDs.get(i));
     if (infoFromBB != null) {
       info = infoFromBB;
     }
     String clientName = info.getClientName();
     if (clientName == null) {
       allOtherVMs.add(info);
       stopModeList.add(TestConfig.tab().stringAt(StopStartPrms.stopModes));
     } else {
       boolean inExcludedNames = false;
       for (String excludeName : excludedClientNames) {
         if (clientName.indexOf(excludeName) >= 0) inExcludedNames = true;
         break;
       }
       if (!inExcludedNames) {
         allOtherVMs.add(info);
         stopModeList.add(TestConfig.tab().stringAt(StopStartPrms.stopModes));
       }
     }
   }
   List<ClientVmInfo> allOtherVMsExceptOne = allOtherVMs.subList(0, allOtherVMs.size() - 1);
   List<String> stopModesExceptOne = stopModeList.subList(0, stopModeList.size() - 1);
   ClientVmInfo remainingVM = allOtherVMs.get(allOtherVMs.size() - 1);
   String remainingStopMode = stopModeList.get(stopModeList.size() - 1);
   return new Object[] {
     allOtherVMsExceptOne,
     stopModesExceptOne,
     remainingVM,
     remainingStopMode,
     allOtherVMs,
     stopModeList
   };
 }
  /**
   * Get a list of "other" vms, along with stop modes. The "other" vms are any vms other than the
   * currently executing vm. The stop mode for each VM is chosen from util.StopStartPrms.stopMode.
   *
   * @param numVMsToTarget The number of VMs to target for a stop/start.
   * @param clientExcludeStr Any vm name that contains this string as a substring is excluded from
   *     consideration.
   * @throws TestException if there aren't numToTarget VMs available.
   * @returns Object[0] - a List of ClientVmInfos. Object[1] - a List of stop modes. Object[2] - a
   *     List of vms eligible but not chosen.
   */
  public static Object[] getOtherVMsWithExclude(int numToTarget, String clientExcludeStr) {
    Log.getLogWriter().info("Choosing " + numToTarget + " vms (other than this one)");
    // get the VMs; vmList and stopModeList are parallel lists
    ArrayList vmList = new ArrayList();
    ArrayList stopModeList = new ArrayList();
    int myVmID = RemoteTestModule.getMyVmid();

    // put numToTarget in vmList
    List vmInfoList = getAllVMs();
    do {
      if (vmInfoList.size() == 0) {
        throw new TestException(
            "Unable to find "
                + numToTarget
                + " vms to stop with client exclude string "
                + clientExcludeStr
                + "; either a test problem or add StopStartVMs.StopStart_initTask to the test");
      }
      // add a VmId to the list of vms to stop
      int randInt = TestConfig.tab().getRandGen().nextInt(0, vmInfoList.size() - 1);
      Object anObj = vmInfoList.get(randInt);
      if (anObj instanceof ClientVmInfo) {
        ClientVmInfo info = (ClientVmInfo) (anObj);
        if (info.getVmid().intValue() != myVmID) { // info is not the current VM
          if ((clientExcludeStr != null) && (info.getClientName().indexOf(clientExcludeStr) >= 0)) {
            // exclude this vm
          } else {
            vmList.add(info);

            // choose a stopMode
            String choice = TestConfig.tab().stringAt(StopStartPrms.stopModes);
            stopModeList.add(choice);
          }
        }
      }
      vmInfoList.remove(randInt);
    } while (vmList.size() < numToTarget);
    return new Object[] {vmList, stopModeList, vmInfoList};
  }
  @Test
  public void testSyncGetTimeouts() throws Exception {
    final String key = "timeoutTestKey";
    final String value = "timeoutTestValue";

    int j = 0;
    boolean set = false;

    // Do not execute this for CI
    if (TestConfig.isCITest()) {
      return;
    }

    do {
      set = client.set(key, 0, value).get();
      j++;
    } while (!set && j < 10);
    assert set;

    // Shutting down the default client to get one with a short timeout.
    assertTrue("Couldn't shut down within five seconds", client.shutdown(5, TimeUnit.SECONDS));

    syncGetTimeoutsInitClient();
    Thread.sleep(100); // allow connections to be established

    int i = 0;
    GetFuture<Object> g = null;
    try {
      for (i = 0; i < 1000000; i++) {
        g = client.asyncGet(key);
        g.get();
      }
      throw new Exception("Didn't get a timeout.");
    } catch (Exception e) {
      assert !g.getStatus().isSuccess();
      System.err.println("Got a timeout at iteration " + i + ".");
    }
    Thread.sleep(100); // let whatever caused the timeout to pass
    try {
      if (value.equals(client.asyncGet(key).get(30, TimeUnit.SECONDS))) {
        System.err.println("Got the right value.");
      } else {
        throw new Exception("Didn't get the expected value.");
      }
    } catch (java.util.concurrent.TimeoutException timeoutException) {
      debugNodeInfo(client.getNodeLocator().getAll());
      throw new Exception("Unexpected timeout after 30 seconds waiting", timeoutException);
    }
  }
 @Test
 public void testBroadcastAfterShutdown() throws Exception {
   String current_config = null;
   Collection<NodeEndPoint> endpoints = new ArrayList<NodeEndPoint>();
   if (TestConfig.getInstance().getClientMode().equals(ClientMode.Dynamic)
       && !TestConfig.getInstance().getEngineType().isSetConfigSupported()) {
     current_config = getCurrentConfigAndClusterEndpoints(client, endpoints);
   }
   client.shutdown();
   try {
     Future<?> f = client.flush();
     fail("Expected IllegalStateException, got " + f.get());
   } catch (IllegalStateException e) {
     // OK
   } finally {
     if (TestConfig.getInstance().getClientMode().equals(ClientMode.Dynamic)
         && !TestConfig.getInstance().getEngineType().isSetConfigSupported()) {
       Thread.sleep(1000);
       restoreClusterConfig(current_config, endpoints);
       Thread.sleep(1000); // Wait for the config to restore
     }
     initClient(); // init for tearDown
   }
 }
Example #24
0
  @Test
  @Category(IntegrationTest.class)
  public void addCommentWithMentionSucceeds() {
    BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken());
    BoxFolder rootFolder = BoxFolder.getRootFolder(api);
    String fileName = "[addCommentSucceeds] Test File.txt";
    byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8);
    String commentMessage =
        String.format(
            "Message mentioning @[%s:%s]",
            TestConfig.getCollaboratorID(), TestConfig.getCollaborator());
    String expectedCommentMessage = "Message mentioning " + TestConfig.getCollaborator();

    InputStream uploadStream = new ByteArrayInputStream(fileBytes);
    BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource();
    BoxComment.Info addedCommentInfo = uploadedFile.addComment(commentMessage);

    assertThat(addedCommentInfo.getMessage(), is(equalTo(expectedCommentMessage)));
    assertThat(
        uploadedFile.getComments(),
        hasItem(Matchers.<BoxComment.Info>hasProperty("ID", equalTo(addedCommentInfo.getID()))));

    uploadedFile.delete();
  }
 /** Initialize fields for this instance */
 public void initializeInstance() {
   numNewKeys = TestConfig.tab().intAt(CQUtilPrms.numNewKeys, -1);
   keyIntervals = (KeyIntervals) (CQUtilBB.getBB().getSharedMap().get(CQUtilBB.KeyIntervals));
   Log.getLogWriter()
       .info("initInstance, keyIntervals read from blackboard = " + keyIntervals.toString());
   int numDestroyed = keyIntervals.getNumKeys(KeyIntervals.DESTROY);
   int numKeyIntervals = keyIntervals.getNumKeys();
   totalNumKeys = numKeyIntervals + numNewKeys - numDestroyed;
   minTaskGranularitySec = TestConfig.tab().longAt(TestHelperPrms.minTaskGranularitySec, -1);
   minTaskGranularityMS = -1;
   if (minTaskGranularitySec != -1) {
     minTaskGranularityMS = minTaskGranularitySec * TestHelper.SEC_MILLI_FACTOR;
   }
   queryDepth = TestConfig.tab().intAt(CQUtilPrms.queryDepth, 1);
   Vector bridgeNames = TestConfig.tab().vecAt(BridgePrms.names, null);
   isBridgeConfiguration = bridgeNames != null;
   CQsOn = TestConfig.tab().booleanAt(CQUtilPrms.CQsOn, true);
   CQTestInstance = new CQTest();
   CQTestInstance.initializeInstance();
   Log.getLogWriter().info("numKeyIntervals is " + numKeyIntervals);
   Log.getLogWriter().info("numNewKeys is " + numNewKeys);
   Log.getLogWriter().info("numDestroyed is " + numDestroyed);
   Log.getLogWriter().info("totalNumKeys is " + totalNumKeys);
 }
 /**
  * Returns the {@link AsyncEventQueueDescription} with the given configuration name from {@link
  * AsyncEventQueuePrms#names}.
  */
 public static AsyncEventQueueDescription getAsyncEventQueueDescription(
     String asyncEventQueueConfig) {
   if (asyncEventQueueConfig == null) {
     throw new IllegalArgumentException("asyncEventQueueConfig cannot be null");
   }
   log.info("Looking up async event queue config: " + asyncEventQueueConfig);
   AsyncEventQueueDescription aeqd =
       TestConfig.getInstance().getAsyncEventQueueDescription(asyncEventQueueConfig);
   if (aeqd == null) {
     String s =
         asyncEventQueueConfig + " not found in " + BasePrms.nameForKey(AsyncEventQueuePrms.names);
     throw new HydraRuntimeException(s);
   }
   log.info("Looked up async event queue config:\n" + aeqd);
   return aeqd;
 }
Example #27
0
  @Test
  @Category(IntegrationTest.class)
  public void updateFileWithSpecialCharsInNameSucceeds() {
    BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken());
    BoxFolder rootFolder = BoxFolder.getRootFolder(api);
    String originalFileName = "[updateFileWithSpecialCharsInNameSucceeds] abc\";def.txt";
    String fileContent = "Test file";
    byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8);

    InputStream uploadStream = new ByteArrayInputStream(fileBytes);
    BoxFile.Info uploadedFileInfo = rootFolder.uploadFile(uploadStream, originalFileName);
    BoxFile uploadedFile = uploadedFileInfo.getResource();

    assertThat(uploadedFileInfo.getName(), is(equalTo(originalFileName)));

    uploadedFile.delete();
  }
Example #28
0
  @Test
  @Category(IntegrationTest.class)
  public void addCommentSucceeds() {
    BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken());
    BoxFolder rootFolder = BoxFolder.getRootFolder(api);
    String fileName = "[addCommentSucceeds] Test File.txt";
    byte[] fileBytes = "Non-empty string".getBytes(StandardCharsets.UTF_8);
    String commentMessage = "Non-empty message";

    InputStream uploadStream = new ByteArrayInputStream(fileBytes);
    BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource();
    BoxComment.Info addedCommentInfo = uploadedFile.addComment(commentMessage);

    assertThat(addedCommentInfo.getMessage(), is(equalTo(commentMessage)));

    uploadedFile.delete();
  }
 protected void initializeQueryService() {
   try {
     String usingPool = TestConfig.tab().stringAt(CQUtilPrms.QueryServiceUsingPool, "false");
     boolean queryServiceUsingPool = Boolean.valueOf(usingPool).booleanValue();
     if (queryServiceUsingPool) {
       Pool pool = PoolHelper.createPool(CQUtilPrms.getQueryServicePoolName());
       qService = pool.getQueryService();
       Log.getLogWriter()
           .info("Initializing QueryService using Pool. PoolName: " + pool.getName());
     } else {
       qService = CacheHelper.getCache().getQueryService();
       Log.getLogWriter().info("Initializing QueryService using Cache.");
     }
   } catch (Exception e) {
     throw new TestException(TestHelper.getStackTrace(e));
   }
 }
Example #30
0
  @Test
  @Category(IntegrationTest.class)
  public void getThumbnail() {
    BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken());
    BoxFolder rootFolder = BoxFolder.getRootFolder(api);
    String fileName = "[getPreviewLink] Test File.txt";
    String fileContent = "Test file";
    byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8);
    InputStream uploadStream = new ByteArrayInputStream(fileBytes);
    BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource();

    byte[] thumbnail = uploadedFile.getThumbnail(BoxFile.ThumbnailFileType.PNG, 256, 256, 256, 256);

    assertThat(thumbnail, is(notNullValue()));
    assertNotEquals(thumbnail.length, 0);

    uploadedFile.delete();
  }