@Test
 public void testNotEquals() throws UnsupportedEncodingException {
   STSInstanceConfig instance1 = buildConfig();
   STSInstanceConfig instance2 = buildConfigWithSaml2Config();
   assertFalse(instance2.equals(instance1));
   assertFalse(instance1.equals(instance2));
 }
Beispiel #2
0
  @Test
  public void testEncryptPassword() throws IOException {
    database.open("admin", "admin");

    Integer updated =
        database
            .command(new OCommandSQL("update ouser set password = '******' where name = 'reader'"))
            .execute();
    Assert.assertEquals(updated.intValue(), 1);

    List<ODocument> result =
        database.query(new OSQLSynchQuery<Object>("select from ouser where name = 'reader'"));
    Assert.assertFalse(result.get(0).field("password").equals("test"));

    // RESET OLD PASSWORD
    updated =
        database
            .command(new OCommandSQL("update ouser set password = '******' where name = 'reader'"))
            .execute();
    Assert.assertEquals(updated.intValue(), 1);

    result = database.query(new OSQLSynchQuery<Object>("select from ouser where name = 'reader'"));
    Assert.assertFalse(result.get(0).field("password").equals("reader"));

    database.close();
  }
  @Override
  public void delete() {
    cancelListeners(getHibernateDao());

    Long pid = Long.valueOf(6L);
    Product product = dao.read(pid);
    Assert.assertNotNull(product);
    Set<User> authorizedUsers = product.getAuthorizedUsers();

    List<MetadataIndex> indexes = product.getIndexes();
    Assert.assertNotNull(indexes);
    Assert.assertFalse(indexes.isEmpty());
    Assert.assertFalse(authorizedUsers.isEmpty());

    dao.delete(product);
    getHibernateDao().getSessionFactory().getCurrentSession().flush();

    Assert.assertNull(dao.read(pid));
    Assert.assertEquals(countElements("METADATA_INDEXES", pid), 0);
    Assert.assertEquals(countElements("CHECKSUMS", pid), 0);

    for (User user : authorizedUsers) {
      Assert.assertNotNull(udao.read(user.getUUID()));
    }
  }
Beispiel #4
0
  @Test(timeOut = 10_000)
  public void testBatchFactoryFunctionality() throws Exception {

    // Component to test
    Batch.BatchFactory factory = new Batch.BatchFactory(BATCH_SIZE);

    // Check the factory creates a new batch properly...
    Batch batch = factory.create();
    assertTrue(batch.isEmpty(), "Batch should be empty");
    assertFalse(batch.isFull(), "Batch shouldn't be full");
    assertEquals(batch.getNumEvents(), 0, "Num events should be 0");

    // ...and is wrapped in to a pooled object
    PooledObject<Batch> pooledBatch = factory.wrap(batch);
    assertEquals(pooledBatch.getObject(), batch);

    // Put some elements in the batch...
    batch.addTimestamp(ANY_ST, channel, monCtx);
    batch.addCommit(ANY_ST, ANY_CT, channel, monCtx);
    batch.addCommitRetry(ANY_ST, channel, monCtx);
    batch.addAbort(ANY_ST, channel, monCtx);
    assertFalse(batch.isEmpty(), "Batch should contain elements");
    assertFalse(batch.isFull(), "Batch should NOT be full");
    assertEquals(batch.getNumEvents(), 4, "Num events should be 4");

    // ... and passivate the object through the factory. It should reset the state of the batch
    factory.passivateObject(pooledBatch);
    assertTrue(batch.isEmpty(), "Batch should NOT contain elements");
    assertFalse(batch.isFull(), "Batch should NOT be full");
    assertEquals(batch.getNumEvents(), 0, "Num events should be 0");
  }
  @Test(dependsOnMethods = "testSubmit")
  public void testGetTypeNames() throws Exception {
    WebResource resource = service.path("api/atlas/types");

    ClientResponse clientResponse =
        resource
            .accept(Servlets.JSON_MEDIA_TYPE)
            .type(Servlets.JSON_MEDIA_TYPE)
            .method(HttpMethod.GET, ClientResponse.class);
    assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode());

    String responseAsString = clientResponse.getEntity(String.class);
    Assert.assertNotNull(responseAsString);

    JSONObject response = new JSONObject(responseAsString);
    Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID));

    final JSONArray list = response.getJSONArray(AtlasClient.RESULTS);
    Assert.assertNotNull(list);

    // Verify that primitive and core types are not returned
    String typesString = list.join(" ");
    Assert.assertFalse(typesString.contains(" \"__IdType\" "));
    Assert.assertFalse(typesString.contains(" \"string\" "));
  }
  /** Test of blobExists method, of class FilesystemAsyncBlobStore. */
  public void testBlobExists() throws IOException {
    boolean result;
    String blobKey;

    // when location doesn't exists
    blobKey = TestUtils.createRandomBlobKey();
    try {
      blobStore.blobExists(CONTAINER_NAME, blobKey);
      fail();
    } catch (ContainerNotFoundException cnfe) {
      // expected
    }

    // when location exists
    blobStore.createContainerInLocation(null, CONTAINER_NAME);
    result = blobStore.blobExists(CONTAINER_NAME, blobKey);
    assertFalse(result, "Blob exists");

    // create blob
    TestUtils.createBlobAsFile(CONTAINER_NAME, blobKey, TestUtils.getImageForBlobPayload());
    result = blobStore.blobExists(CONTAINER_NAME, blobKey);
    assertTrue(result, "Blob doesn't exist");

    // complex path test
    blobKey = TestUtils.createRandomBlobKey("ss/asdas/", "");
    result = blobStore.blobExists(CONTAINER_NAME, blobKey);
    assertFalse(result, "Blob exists");
    TestUtils.createBlobAsFile(CONTAINER_NAME, blobKey, TestUtils.getImageForBlobPayload());
    result = blobStore.blobExists(CONTAINER_NAME, blobKey);
    assertTrue(result, "Blob doesn't exist");
  }
  @Test
  public void testTimeRetention() throws Exception {
    TimeRetentionStrategy retentionStrategy = new TimeRetentionStrategy("DAYS", "30");

    SegmentZKMetadata metadata = new OfflineSegmentZKMetadata();
    metadata.setTimeUnit(TimeUnit.DAYS);

    // Set end time to Jan 2nd, 1970 (not purgeable due to bogus timestamp)
    metadata.setEndTime(1L);
    assertFalse(retentionStrategy.isPurgeable(metadata));

    // Set end time to today
    final long today = TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis());
    metadata.setEndTime(today);
    assertFalse(retentionStrategy.isPurgeable(metadata));

    // Set end time to two weeks ago
    metadata.setEndTime(today - 14);
    assertFalse(retentionStrategy.isPurgeable(metadata));

    // Set end time to two months ago (purgeable due to being past the retention period)
    metadata.setEndTime(today - 60);
    assertTrue(retentionStrategy.isPurgeable(metadata));

    // Set end time to 200 years in the future (not purgeable due to bogus timestamp)
    metadata.setEndTime(today + (365 * 200));
    assertFalse(retentionStrategy.isPurgeable(metadata));
  }
Beispiel #8
0
  @Test(dataProvider = "HiSeqVCFHeaderDataProvider")
  public void testVCFHeaderAddOtherLine(final VCFHeader header) {
    final VCFHeaderLine otherLine = new VCFHeaderLine("TestOtherLine", "val");
    header.addMetaDataLine(otherLine);

    Assert.assertTrue(
        header.getOtherHeaderLines().contains(otherLine),
        "TestOtherLine not found in other header lines");
    Assert.assertTrue(
        header.getMetaDataInInputOrder().contains(otherLine),
        "TestOtherLine not found in set of all header lines");
    Assert.assertNotNull(
        header.getOtherHeaderLine("TestOtherLine"), "Lookup for TestOtherLine by key failed");

    Assert.assertFalse(
        header.getInfoHeaderLines().contains(otherLine),
        "TestOtherLine present in info header lines");
    Assert.assertFalse(
        header.getFormatHeaderLines().contains(otherLine),
        "TestOtherLine present in format header lines");
    Assert.assertFalse(
        header.getContigLines().contains(otherLine),
        "TestOtherLine present in contig header lines");
    Assert.assertFalse(
        header.getFilterLines().contains(otherLine),
        "TestOtherLine present in filter header lines");
  }
  private void testProcessLeftBelowFilesAllClean() throws Exception {
    final HadoopWriterFactory factory = new NoWriteHadoopWriterFactory(null, config);

    FileUtils.touch(new File(lockDirectory.getPath() + "/some_file_which_should_be_sent_1"));
    FileUtils.touch(new File(lockDirectory.getPath() + "/some_file_which_should_be_sent_2"));
    FileUtils.touch(
        new File(quarantineDirectory.getPath() + "/some_other_file_which_should_be_sent"));

    Assert.assertEquals(
        FileUtils.listFiles(
                spoolDirectory, FileFilterUtils.trueFileFilter(), FileFilterUtils.trueFileFilter())
            .size(),
        3);
    Assert.assertTrue(spoolDirectory.exists());
    Assert.assertTrue(tmpDirectory.exists());
    Assert.assertTrue(lockDirectory.exists());
    Assert.assertTrue(quarantineDirectory.exists());

    Thread.sleep(2 * CUTOFF_TIME);
    factory.processLeftBelowFiles();

    // All files should have been sent
    Assert.assertFalse(spoolDirectory.exists());
    Assert.assertFalse(tmpDirectory.exists());
    Assert.assertFalse(lockDirectory.exists());
    Assert.assertFalse(quarantineDirectory.exists());

    // We could even test the mapping in HDFS here (with the keys)
    Assert.assertEquals(hdfs.values().size(), 3);
  }
  /*
   * Test for Duration.isSet().
   */
  @Test
  public void checkDurationIsSet() {
    Duration duration1 = datatypeFactory.newDuration(true, 1, 1, 1, 1, 1, 1);
    Duration duration2 = datatypeFactory.newDuration(true, 0, 0, 0, 0, 0, 0);

    assertTrue(duration1.isSet(YEARS));
    assertTrue(duration1.isSet(MONTHS));
    assertTrue(duration1.isSet(DAYS));
    assertTrue(duration1.isSet(HOURS));
    assertTrue(duration1.isSet(MINUTES));
    assertTrue(duration1.isSet(SECONDS));

    assertTrue(duration2.isSet(YEARS));
    assertTrue(duration2.isSet(MONTHS));
    assertTrue(duration2.isSet(DAYS));
    assertTrue(duration2.isSet(HOURS));
    assertTrue(duration2.isSet(MINUTES));
    assertTrue(duration2.isSet(SECONDS));

    Duration duration66 = datatypeFactory.newDuration(true, null, null, zero, null, null, null);
    assertFalse(duration66.isSet(YEARS));
    assertFalse(duration66.isSet(MONTHS));
    assertFalse(duration66.isSet(HOURS));
    assertFalse(duration66.isSet(MINUTES));
    assertFalse(duration66.isSet(SECONDS));

    Duration duration3 = datatypeFactory.newDuration("P1D");
    assertFalse(duration3.isSet(YEARS));
    assertFalse(duration3.isSet(MONTHS));
    assertFalse(duration3.isSet(HOURS));
    assertFalse(duration3.isSet(MINUTES));
    assertFalse(duration3.isSet(SECONDS));
  }
Beispiel #11
0
  @Test(dataProvider = "HiSeqVCFHeaderDataProvider")
  public void testVCFHeaderAddContigLine(final VCFHeader header) {
    final VCFContigHeaderLine contigLine =
        new VCFContigHeaderLine(
            "<ID=chr1,length=1234567890,assembly=FAKE,md5=f126cdf8a6e0c7f379d618ff66beb2da,species=\"H**o sapiens\">",
            VCFHeaderVersion.VCF4_0,
            "chr1",
            0);
    header.addMetaDataLine(contigLine);

    Assert.assertTrue(
        header.getContigLines().contains(contigLine),
        "Test contig line not found in contig header lines");
    Assert.assertTrue(
        header.getMetaDataInInputOrder().contains(contigLine),
        "Test contig line not found in set of all header lines");

    Assert.assertFalse(
        header.getInfoHeaderLines().contains(contigLine),
        "Test contig line present in info header lines");
    Assert.assertFalse(
        header.getFormatHeaderLines().contains(contigLine),
        "Test contig line present in format header lines");
    Assert.assertFalse(
        header.getFilterLines().contains(contigLine),
        "Test contig line present in filter header lines");
    Assert.assertFalse(
        header.getOtherHeaderLines().contains(contigLine),
        "Test contig line present in other header lines");
  }
  @Test
  public void allow() throws MalformedObjectNameException {
    InputStream is = getClass().getResourceAsStream("/access-sample5.xml");
    PolicyRestrictor restrictor = new PolicyRestrictor(is);
    assertTrue(
        restrictor.isAttributeReadAllowed(
            new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"));
    assertTrue(
        restrictor.isAttributeWriteAllowed(
            new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage"));
    assertTrue(
        restrictor.isAttributeReadAllowed(
            new ObjectName("java.lang:type=Memory"), "NonHeapMemoryUsage"));
    assertFalse(
        restrictor.isAttributeWriteAllowed(
            new ObjectName("java.lang:type=Memory"), "NonHeapMemoryUsage"));
    assertFalse(
        restrictor.isAttributeReadAllowed(new ObjectName("java.lang:type=Memory"), "BlaUsage"));

    assertTrue(restrictor.isAttributeReadAllowed(new ObjectName("jolokia:type=Config"), "Debug"));

    assertTrue(
        restrictor.isOperationAllowed(new ObjectName("java.lang:type=Blubber,name=x"), "gc"));
    assertFalse(
        restrictor.isOperationAllowed(new ObjectName("java.lang:type=Blubber,name=x"), "xavier"));
  }
Beispiel #13
0
  /**
   * Test setter and getter call and make sure they match.
   *
   * <p>
   *
   * @param property the property to be set
   * @param setValue the value to be set
   * @param qName qualified name for error reporting
   */
  private static void testProperty(
      Object target, PropertyDescriptor property, Object setValue, String qName) {

    // flag indicating whether a comparison should be done at the end
    boolean expectMatch = true;

    // call setter (if exists)
    if (property.getWriteMethod() != null) {
      invokeMethod(target, property.getWriteMethod(), new Object[] {setValue}, qName);
    } else {
      Assert.assertFalse(true, "Property " + qName + " does not have the required setter.");
      expectMatch = false;
    }

    // call getter (if exists)
    Object getValue = null;
    if (property.getReadMethod() != null) {
      getValue = invokeMethod(target, property.getReadMethod(), null, qName);
    } else {
      Assert.assertFalse(true, "Property " + qName + " does not have the required getter.");
      expectMatch = false;
    }

    // if expecting a match, compare
    // if they are not the same instance, assert that they have equality
    if (expectMatch && setValue != getValue)
      Assert.assertEquals(
          getValue, setValue, "Values did not match for getter/setter call on field " + qName);
  }
 @Test(
     groups = "wso2.esb",
     description =
         "test to verify that the soap builder/formatter is invoked properly"
             + "when the soap request is made after rest request.")
 public void testSendingSoapCallAfterRestCall() throws Exception {
   String restURL =
       getApiInvocationURL(
           "api_poc_messagetype"); // esbServer.getServiceUrl() + "/testmessagetype";
   DefaultHttpClient httpclient = new DefaultHttpClient();
   HttpGet request = new HttpGet(restURL);
   HttpResponse response = httpclient.execute(request);
   BufferedReader rd =
       new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
   String responseText = "";
   String line = "";
   while ((line = rd.readLine()) != null) {
     responseText = responseText.concat(line);
   }
   assertFalse(
       responseText.contains("soapenv:Envelope"),
       "Another <soapenv:Envelope> tag found inside soap body.");
   assertFalse(
       responseText.contains("soapenv:Body"),
       "Another <soapenv:Body> tag found inside soap body.");
 }
  public void testRemoveBlob_TwoSimpleBlobKeys() throws IOException {
    final String BLOB_KEY1 = TestUtils.createRandomBlobKey(null, null);
    final String BLOB_KEY2 = TestUtils.createRandomBlobKey(null, null);
    boolean result;

    // create the container and checks that blob doesn't exists
    blobStore.createContainerInLocation(null, CONTAINER_NAME);
    result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY1);
    assertFalse(result, "Blob1 exists");
    result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY2);
    assertFalse(result, "Blob2 exists");

    // create the blob
    TestUtils.createBlobsInContainer(CONTAINER_NAME, BLOB_KEY1, BLOB_KEY2);
    result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY1);
    assertTrue(result, "Blob " + BLOB_KEY1 + " doesn't exist");
    result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY2);
    assertTrue(result, "Blob " + BLOB_KEY2 + " doesn't exist");

    // remove first blob
    blobStore.removeBlob(CONTAINER_NAME, BLOB_KEY1);
    result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY1);
    assertFalse(result, "Blob1 still exists");
    result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY2);
    assertTrue(result, "Blob2 doesn't exist");
    TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + BLOB_KEY1, false);
    TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + BLOB_KEY2, true);
    // remove second blob
    blobStore.removeBlob(CONTAINER_NAME, BLOB_KEY2);
    result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY2);
    assertFalse(result, "Blob2 still exists");
    TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + BLOB_KEY2, false);
  }
Beispiel #16
0
  public void updateSetMultipleFields() {

    List<ODocument> result1 =
        database
            .command(new OCommandSQL("select salary from Account where salary is defined"))
            .execute();
    Assert.assertFalse(result1.isEmpty());

    updatedRecords =
        database
            .command(
                new OCommandSQL(
                    "update Account set salary2 = salary, checkpoint = true where salary is defined"))
            .execute();
    Assert.assertTrue(updatedRecords > 0);

    List<ODocument> result2 =
        database.command(new OCommandSQL("select from Account where salary is defined")).execute();
    Assert.assertFalse(result2.isEmpty());
    Assert.assertEquals(result2.size(), result1.size());

    for (int i = 0; i < result1.size(); ++i) {
      float salary1 = result1.get(i).field("salary");
      float salary2 = result2.get(i).field("salary2");
      Assert.assertEquals(salary2, salary1);
      Assert.assertEquals(result2.get(i).field("checkpoint"), true);
    }
  }
  /** Test of removeBlob method, with only one blob with a complex path as key */
  @Test
  public void testRemoveBlob_ComplexBlobKey() throws IOException {
    final String BLOB_KEY = TestUtils.createRandomBlobKey("aa/bb/cc/dd/", null);
    boolean result;

    // checks that blob doesn't exists
    blobStore.createContainerInLocation(null, CONTAINER_NAME);
    result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY);
    assertFalse(result, "Blob exists");
    TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + BLOB_KEY, false);

    // create the blob
    TestUtils.createBlobsInContainer(CONTAINER_NAME, BLOB_KEY);
    result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY);
    assertTrue(result, "Blob doesn't exist");

    // remove it
    blobStore.removeBlob(CONTAINER_NAME, BLOB_KEY);
    result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY);
    assertFalse(result, "Blob still exists");
    // file removed
    TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + BLOB_KEY, false);
    // also the entire directory structure was removed
    TestUtils.directoryExists(TARGET_CONTAINER_NAME + "/aa", false);
  }
  @Test(groups = "fast")
  public void testInvoiceAdjustment() throws Exception {
    final UUID invoiceId = UUID.randomUUID();

    Assert.assertFalse(
        BusinessInvoiceUtils.isInvoiceAdjustmentItem(
            createInvoiceItem(invoiceId, InvoiceItemType.RECURRING),
            ImmutableList.<InvoiceItem>of()));

    final InvoiceItem creditAdj = createInvoiceItem(invoiceId, InvoiceItemType.CREDIT_ADJ);

    // Account credit
    Assert.assertFalse(
        BusinessInvoiceUtils.isInvoiceAdjustmentItem(
            creditAdj,
            ImmutableList.<InvoiceItem>of(
                createInvoiceItem(
                    invoiceId, InvoiceItemType.CBA_ADJ, creditAdj.getAmount().negate()))));

    Assert.assertTrue(
        BusinessInvoiceUtils.isInvoiceAdjustmentItem(
            creditAdj,
            ImmutableList.<InvoiceItem>of(
                createInvoiceItem(
                    invoiceId,
                    InvoiceItemType.CBA_ADJ,
                    creditAdj.getAmount().negate().add(BigDecimal.ONE)))));
    Assert.assertTrue(
        BusinessInvoiceUtils.isInvoiceAdjustmentItem(
            creditAdj,
            ImmutableList.<InvoiceItem>of(
                createInvoiceItem(invoiceId, InvoiceItemType.RECURRING),
                createInvoiceItem(
                    invoiceId, InvoiceItemType.CBA_ADJ, creditAdj.getAmount().negate()))));
  }
Beispiel #19
0
  @Test
  public void testIsTypeOnlyCoercion() {
    assertTrue(typeRegistry.isTypeOnlyCoercion(BIGINT, BIGINT));
    assertTrue(isTypeOnlyCoercion("varchar(42)", "varchar(44)"));
    assertFalse(isTypeOnlyCoercion("varchar(44)", "varchar(42)"));

    assertTrue(isTypeOnlyCoercion("array(varchar(42))", "array(varchar(44))"));
    assertFalse(isTypeOnlyCoercion("array(varchar(44))", "array(varchar(42))"));

    assertTrue(isTypeOnlyCoercion("decimal(22,1)", "decimal(23,1)"));
    assertTrue(isTypeOnlyCoercion("decimal(2,1)", "decimal(3,1)"));
    assertFalse(isTypeOnlyCoercion("decimal(23,1)", "decimal(22,1)"));
    assertFalse(isTypeOnlyCoercion("decimal(3,1)", "decimal(2,1)"));
    assertFalse(isTypeOnlyCoercion("decimal(3,1)", "decimal(22,1)"));

    assertTrue(isTypeOnlyCoercion("array(decimal(22,1))", "array(decimal(23,1))"));
    assertTrue(isTypeOnlyCoercion("array(decimal(2,1))", "array(decimal(3,1))"));
    assertFalse(isTypeOnlyCoercion("array(decimal(23,1))", "array(decimal(22,1))"));
    assertFalse(isTypeOnlyCoercion("array(decimal(3,1))", "array(decimal(2,1))"));

    assertTrue(
        isTypeOnlyCoercion("map(decimal(2,1), decimal(2,1))", "map(decimal(2,1), decimal(3,1))"));
    assertFalse(
        isTypeOnlyCoercion("map(decimal(2,1), decimal(2,1))", "map(decimal(2,1), decimal(23,1))"));
    assertFalse(
        isTypeOnlyCoercion("map(decimal(2,1), decimal(2,1))", "map(decimal(2,1), decimal(3,2))"));
    assertTrue(
        isTypeOnlyCoercion("map(decimal(22,1), decimal(2,1))", "map(decimal(23,1), decimal(3,1))"));
    assertFalse(
        isTypeOnlyCoercion("map(decimal(23,1), decimal(3,1))", "map(decimal(22,1), decimal(2,1))"));
  }
  @Test
  public void testRunning() {
    StageStateMachine stateMachine = createStageStateMachine();
    assertTrue(stateMachine.transitionToRunning());
    assertState(stateMachine, StageState.RUNNING);

    assertFalse(stateMachine.transitionToScheduling());
    assertState(stateMachine, StageState.RUNNING);

    assertFalse(stateMachine.transitionToScheduled());
    assertState(stateMachine, StageState.RUNNING);

    assertFalse(stateMachine.transitionToRunning());
    assertState(stateMachine, StageState.RUNNING);

    assertTrue(stateMachine.transitionToFinished());
    assertState(stateMachine, StageState.FINISHED);

    stateMachine = createStageStateMachine();
    stateMachine.transitionToRunning();
    assertTrue(stateMachine.transitionToFailed(FAILED_CAUSE));
    assertState(stateMachine, StageState.FAILED);

    stateMachine = createStageStateMachine();
    stateMachine.transitionToRunning();
    assertTrue(stateMachine.transitionToAborted());
    assertState(stateMachine, StageState.ABORTED);

    stateMachine = createStageStateMachine();
    stateMachine.transitionToRunning();
    assertTrue(stateMachine.transitionToCanceled());
    assertState(stateMachine, StageState.CANCELED);
  }
Beispiel #21
0
  @Test
  public void isVirtualTest() {

    Assert.assertFalse((new TableName("virtual", "virtual").isVirtual()));
    Assert.assertFalse((new TableName("virtual", Constants.VIRTUAL_NAME).isVirtual()));
    Assert.assertTrue((new TableName(Constants.VIRTUAL_NAME, "").isVirtual()));
  }
 private void validateInjectionPoints(Set<InjectionPoint> injectionPoints) {
   assertEquals(2, injectionPoints.size());
   for (InjectionPoint ip : injectionPoints) {
     AnnotatedParameter<Factory> parameter =
         this.<AnnotatedParameter<Factory>>cast(ip.getAnnotated());
     if (parameter.getPosition() == 0) {
       // BeanManager
       assertEquals(BeanManager.class, parameter.getBaseType());
     } else if (parameter.getPosition() == 1) {
       // SpaceSuit<Toy>
       Type baseType = parameter.getBaseType();
       if (baseType instanceof ParameterizedType
           && ((ParameterizedType) baseType).getRawType() instanceof Class<?>) {
         assertEquals(((ParameterizedType) baseType).getRawType(), SpaceSuit.class);
       } else {
         fail();
       }
     } else {
       fail("Unexpected injection point " + ip);
     }
     assertFalse(ip.isDelegate());
     assertFalse(ip.isTransient());
     assertNull(ip.getBean());
   }
 }
Beispiel #23
0
  @Test
  public void testPrefix() throws Exception {
    // Check client path prefix
    final HawkClient testClient1 =
        new HawkClient.Builder().credentials(this.testcredentials1).build();
    assertTrue(testClient1.isValidFor("/test/test2"));
    assertTrue(testClient1.isValidFor(null));

    HawkClientConfiguration clientConfiguration =
        new HawkClientConfiguration.Builder().pathPrefix("/foo").build();
    final HawkClient testClient2 =
        new HawkClient.Builder()
            .credentials(this.testcredentials1)
            .configuration(clientConfiguration)
            .build();
    assertTrue(testClient2.isValidFor("/foo"));
    assertFalse(testClient2.isValidFor("/test/test2"));

    clientConfiguration =
        new HawkClientConfiguration.Builder(clientConfiguration).pathPrefix("/test/").build();
    final HawkClient testClient3 =
        new HawkClient.Builder()
            .credentials(this.testcredentials1)
            .configuration(clientConfiguration)
            .build();
    assertTrue(testClient3.isValidFor("/test/test2"));
    assertFalse(testClient3.isValidFor("/testtest2"));
  }
  private void testLocationUnmanagedOnStop(LocationSpec<? extends Location> locationSpec) {
    EntitySpec<BasicApplication> appSpec =
        EntitySpec.create(BasicApplication.class)
            .location(locationSpec)
            .child(
                EntitySpec.create(EmptySoftwareProcess.class)
                    .configure(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION, Boolean.TRUE)
                    .configure(EmptySoftwareProcess.USE_SSH_MONITORING, Boolean.FALSE));

    BasicApplication app = mgmt.getEntityManager().createEntity(appSpec);
    Entity child = Iterables.getOnlyElement(app.getChildren());

    Assert.assertEquals(child.getLocations(), ImmutableList.of());

    app.start(ImmutableList.<Location>of());
    Location appLocation = Iterables.getOnlyElement(app.getLocations());
    assertOwned(app, appLocation);
    Location entityLocation = Iterables.getOnlyElement(child.getLocations());
    // No owner tag because it's created by SoftwareProcess, not by Brooklyn internals
    assertNotOwned(entityLocation);
    app.stop();

    Assert.assertEquals(child.getLocations(), ImmutableList.of());

    Assert.assertFalse(mgmt.getEntityManager().isManaged(child));
    Assert.assertFalse(mgmt.getEntityManager().isManaged(app));
    Set<Location> locs = ImmutableSet.copyOf(mgmt.getLocationManager().getLocations());
    Assert.assertFalse(
        locs.contains(entityLocation), locs + " should not contain " + entityLocation);
    Assert.assertFalse(locs.contains(appLocation), locs + " should not contain " + appLocation);
  }
Beispiel #25
0
  @Test
  public void testAbruptFinish() {
    List<Type> types = ImmutableList.<Type>of(VARCHAR, BIGINT, BIGINT);
    ValuesOperator source =
        new ValuesOperator(
            driverContext.addOperatorContext(0, new PlanNodeId("test"), "values"),
            types,
            rowPagesBuilder(types).addSequencePage(10, 20, 30, 40).build());

    PageConsumerOperator sink = createSinkOperator(source);
    Driver driver = new Driver(driverContext, source, sink);

    assertSame(driver.getDriverContext(), driverContext);

    assertFalse(driver.isFinished());
    driver.close();
    assertTrue(driver.isFinished());

    // finish is only called in normal operations
    assertFalse(source.isFinished());
    assertFalse(sink.isFinished());

    // close is always called (values operator doesn't have a closed state)
    assertTrue(sink.isClosed());
  }
  /** tests the AnnotatedTypes.compareAnnotatedTypes */
  @Test
  public void testComparison()
      throws SecurityException, NoSuchFieldException, NoSuchMethodException {
    // check that two weld classes on the same underlying are equal
    TypeStore ts = new TypeStore();
    String contextId = "STATIC_INSTANCE";
    ClassTransformer ct = new ClassTransformer(contextId, ts);
    WeldClass<Chair> chair1 = WeldClassImpl.of(contextId, Chair.class, ct);
    WeldClass<Chair> chair2 = WeldClassImpl.of(contextId, Chair.class, ct);
    Assert.assertTrue(AnnotatedTypes.compareAnnotatedTypes(chair1, chair2));

    // check that a different implementation of annotated type is equal to the weld implementation
    TestAnnotatedTypeBuilder<Chair> builder = new TestAnnotatedTypeBuilder<Chair>(Chair.class);
    builder.addToClass(new DefaultLiteral());
    builder.addToField(Chair.class.getField("legs"), new ProducesLiteral());
    builder.addToMethod(Chair.class.getMethod("sit"), new ProducesLiteral());
    AnnotatedType<Chair> chair3 = builder.create();
    Assert.assertTrue(AnnotatedTypes.compareAnnotatedTypes(chair1, chair3));

    // check that the implementation returns false if a field annotation changes
    builder = new TestAnnotatedTypeBuilder<Chair>(Chair.class);
    builder.addToClass(new DefaultLiteral());
    builder.addToField(Chair.class.getField("legs"), new DefaultLiteral());
    builder.addToMethod(Chair.class.getMethod("sit"), new ProducesLiteral());
    chair3 = builder.create();
    Assert.assertFalse(AnnotatedTypes.compareAnnotatedTypes(chair1, chair3));

    // check that the implementation returns false if a class level annotation changes
    builder = new TestAnnotatedTypeBuilder<Chair>(Chair.class);
    builder.addToClass(new ProducesLiteral());
    builder.addToField(Chair.class.getField("legs"), new DefaultLiteral());
    builder.addToMethod(Chair.class.getMethod("sit"), new ProducesLiteral());
    chair3 = builder.create();
    Assert.assertFalse(AnnotatedTypes.compareAnnotatedTypes(chair1, chair3));
  }
Beispiel #27
0
  public void testParentRole() {
    database.open("admin", "admin");

    final OSecurity security = database.getMetadata().getSecurity();
    ORole writer = security.getRole("writer");

    ORole writerChild =
        security.createRole("writerChild", writer, OSecurityRole.ALLOW_MODES.ALLOW_ALL_BUT);
    writerChild.save();

    ORole writerGrandChild =
        security.createRole(
            "writerGrandChild", writerChild, OSecurityRole.ALLOW_MODES.ALLOW_ALL_BUT);
    writerGrandChild.save();

    OUser child = security.createUser("writerChild", "writerChild", writerGrandChild);
    child.save();

    Assert.assertTrue(child.hasRole("writer", true));
    Assert.assertFalse(child.hasRole("wrter", true));

    database.close();
    if (!(database.getStorage() instanceof OStorageProxy)) {
      database.open("writerChild", "writerChild");

      OSecurityUser user = database.getUser();
      Assert.assertTrue(user.hasRole("writer", true));
      Assert.assertFalse(user.hasRole("wrter", true));

      database.close();
    }
  }
  @Test(dependsOnMethods = "testOnProcessEntityChange")
  public void testAreSame() throws Exception {

    Inputs inputs1 = new Inputs();
    Inputs inputs2 = new Inputs();
    Outputs outputs1 = new Outputs();
    Outputs outputs2 = new Outputs();
    // return true when both are null
    Assert.assertTrue(EntityRelationshipGraphBuilder.areSame(inputs1, inputs2));
    Assert.assertTrue(EntityRelationshipGraphBuilder.areSame(outputs1, outputs2));

    Input i1 = new Input();
    i1.setName("input1");
    Input i2 = new Input();
    i2.setName("input2");
    Output o1 = new Output();
    o1.setName("output1");
    Output o2 = new Output();
    o2.setName("output2");

    inputs1.getInputs().add(i1);
    Assert.assertFalse(EntityRelationshipGraphBuilder.areSame(inputs1, inputs2));
    outputs1.getOutputs().add(o1);
    Assert.assertFalse(EntityRelationshipGraphBuilder.areSame(outputs1, outputs2));

    inputs2.getInputs().add(i1);
    Assert.assertTrue(EntityRelationshipGraphBuilder.areSame(inputs1, inputs2));
    outputs2.getOutputs().add(o1);
    Assert.assertTrue(EntityRelationshipGraphBuilder.areSame(outputs1, outputs2));
  }
 public void testStandardJob_adjustCacheHints() {
   final CalculationJob job1 =
       new CalculationJob(
           createJobSpecification(),
           0,
           null,
           Arrays.asList(JOB_ITEM_A, JOB_ITEM_AB),
           CacheSelectHint.allPrivate());
   final CalculationJob job2 =
       new CalculationJob(
           createJobSpecification(),
           0,
           new long[] {job1.getSpecification().getJobId()},
           Arrays.asList(JOB_ITEM_BC),
           CacheSelectHint.privateValues(Arrays.asList(VS_B)));
   job1.addTail(job2);
   final CalculationJob adj1 =
       StandardJob.adjustCacheHints(
           job1,
           new HashMap<
               ValueSpecification,
               Triple<
                   CalculationJob,
                   ? extends Set<ValueSpecification>,
                   ? extends Set<ValueSpecification>>>());
   assertNotNull(adj1.getTail());
   final CalculationJob adj2 = adj1.getTail().iterator().next();
   assertEquals(adj1.getJobItems(), job1.getJobItems());
   assertEquals(adj2.getJobItems(), job2.getJobItems());
   assertTrue(adj1.getCacheSelectHint().isPrivateValue(VS_A));
   assertFalse(adj1.getCacheSelectHint().isPrivateValue(VS_B));
   assertFalse(adj2.getCacheSelectHint().isPrivateValue(VS_B));
   assertFalse(adj2.getCacheSelectHint().isPrivateValue(VS_C));
 }
  @Test
  public void testFailsOnVerifyFile() throws Exception {
    File invalidJsonFile = new File(tempStageDir, "invalidjson2.snappy");
    Files.copy(new File(Resources.getResource("invalidjson2.snappy").toURI()), invalidJsonFile);

    assertTrue(invalidJsonFile.exists());
    uploader =
        new S3Uploader(
            storageSystem,
            serverConfig,
            new EventPartitioner(),
            executor,
            executor,
            s3UploaderStats);
    uploader.start();
    assertFalse(invalidJsonFile.exists());
    assertTrue(new File(tempStageDir.getPath() + "/failed", invalidJsonFile.getName()).exists());
    assertFalse(storageSystem.hasReceivedFile(invalidJsonFile));

    S3UploaderStats s3UploaderStatsArgumentVerifier =
        testingReportCollectionFactory.getArgumentVerifier(S3UploaderStats.class);
    verify(s3UploaderStatsArgumentVerifier).processedFiles(UNKNOWN_EVENT_TYPE, CORRUPT);
    verifyNoMoreInteractions(s3UploaderStatsArgumentVerifier);

    CounterStat processedFilesCounterStat =
        testingReportCollectionFactory
            .getReportCollection(S3UploaderStats.class)
            .processedFiles(UNKNOWN_EVENT_TYPE, CORRUPT);
    verify(processedFilesCounterStat).add(1);
    verifyNoMoreInteractions(processedFilesCounterStat);
  }