Java Code Examples for org.apache.brooklyn.util.os.Os#newTempFile()

The following examples show how to use org.apache.brooklyn.util.os.Os#newTempFile() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CatalogResourceTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private static File createZip(Map<String, String> files) throws Exception {
    File f = Os.newTempFile("osgi", "zip");

    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(f));

    for (Map.Entry<String, String> entry : files.entrySet()) {
        ZipEntry ze = new ZipEntry(entry.getKey());
        zip.putNextEntry(ze);
        zip.write(entry.getValue().getBytes());
    }

    zip.closeEntry();
    zip.flush();
    zip.close();

    return f;
}
 
Example 2
Source File: SshFetchTaskWrapper.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public String call() throws Exception {
    int result = -1;
    try {
        Preconditions.checkNotNull(getMachine(), "machine");
        backingFile = Os.newTempFile("brooklyn-ssh-fetch-", FilenameUtils.getName(remoteFile));
        backingFile.deleteOnExit();
        
        result = getMachine().copyFrom(config.getAllConfig(), remoteFile, backingFile.getPath());
    } catch (Exception e) {
        throw new IllegalStateException("SSH fetch "+getRemoteFile()+" from "+getMachine()+" returned threw exception, in "+Tasks.current()+": "+e, e);
    }
    if (result!=0) {
        throw new IllegalStateException("SSH fetch "+getRemoteFile()+" from "+getMachine()+" returned non-zero exit code  "+result+", in "+Tasks.current());
    }
    return FileUtils.readFileToString(backingFile);
}
 
Example 3
Source File: CatalogResourceTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private static File createJar(Map<String, String> files) throws Exception {
    File f = Os.newTempFile("osgi", "jar");

    JarOutputStream zip = new JarOutputStream(new FileOutputStream(f));

    for (Map.Entry<String, String> entry : files.entrySet()) {
        JarEntry ze = new JarEntry(entry.getKey());
        zip.putNextEntry(ze);
        zip.write(entry.getValue().getBytes());
    }

    zip.closeEntry();
    zip.flush();
    zip.close();

    return f;
}
 
Example 4
Source File: FileBasedStoreObjectAccessorWriterTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups={"Integration", "Broken"}, invocationCount=5000)
public void testSimpleOperationsDelay() throws Exception {
    Callable<Void> r = new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            File tmp = Os.newTempFile(getClass(), "txt");
            try(Writer out = new FileWriter(tmp)) {
                out.write(TEST_FILE_CONTENT);
            }
            tmp.delete();
            return null;
        }
    };

    final Future<Void> f1 = executor.submit(r);
    final Future<Void> f2 = executor.submit(r);

    CountdownTimer time = CountdownTimer.newInstanceStarted(FILE_OPERATION_TIMEOUT);
    f1.get(time.getDurationRemaining().toMilliseconds(), TimeUnit.MILLISECONDS);
    f2.get(time.getDurationRemaining().toMilliseconds(), TimeUnit.MILLISECONDS);
}
 
Example 5
Source File: BrooklynWebServer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private String getLocalKeyStorePath(String keystoreUrl) {
    ResourceUtils res = ResourceUtils.create(this);
    res.checkUrlExists(keystoreUrl, BrooklynWebConfig.KEYSTORE_URL.getName());
    if (new File(keystoreUrl).exists()) {
        return keystoreUrl;
    } else {
        InputStream keystoreStream;
        try {
            keystoreStream = res.getResourceFromUrl(keystoreUrl);
        } catch (Exception e) {
            Exceptions.propagateIfFatal(e);
            throw new IllegalArgumentException("Unable to access URL: "+keystoreUrl, e);
        }
        File tmp = Os.newTempFile("brooklyn-keystore", "ks");
        tmp.deleteOnExit();
        try {
            FileUtil.copyTo(keystoreStream, tmp);
        } finally {
            Streams.closeQuietly(keystoreStream);
        }
        return tmp.getAbsolutePath();
    }
}
 
Example 6
Source File: CatalogScanOsgiTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
static void installJavaScanningMoreEntitiesV2(ManagementContext mgmt, Object context) throws FileNotFoundException {
    // scanning bundle functionality added in 0.12.0, relatively new compared to non-osgi scanning
    
    TestResourceUnavailableException.throwIfResourceUnavailable(context.getClass(), OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    TestResourceUnavailableException.throwIfResourceUnavailable(context.getClass(), OsgiTestResources.BROOKLYN_TEST_MORE_ENTITIES_V2_PATH);
    
    CampYamlLiteTest.installWithoutCatalogBom(mgmt, OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    
    BundleMaker bm = new BundleMaker(mgmt);
    File f = Os.newTempFile(context.getClass(), "jar");
    Streams.copy(ResourceUtils.create(context).getResourceFromUrl(OsgiTestResources.BROOKLYN_TEST_MORE_ENTITIES_V2_PATH), new FileOutputStream(f));
    f = bm.copyRemoving(f, MutableSet.of("catalog.bom"));
    f = bm.copyAdding(f, MutableMap.of(new ZipEntry("catalog.bom"),
        new ByteArrayInputStream( Strings.lines(
            "brooklyn.catalog:",
            "  scanJavaAnnotations: true").getBytes() ) ));
    
    ((ManagementContextInternal)mgmt).getOsgiManager().get().install(new FileInputStream(f)).checkNoError();
}
 
Example 7
Source File: SecureKeysAndSignerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadRsaPassphraseKeyAndWriteWithoutPassphrase() throws Exception {
    KeyPair key = readPem("classpath://brooklyn/util/crypto/sample_rsa_passphrase.pem", "passphrase");
    checkNonTrivial(key);
    File f = Os.newTempFile(getClass(), "brooklyn-sample_rsa_passphrase_without_passphrase.pem");
    Files.write(SecureKeys.toPem(key), f, Charset.defaultCharset());
    KeyPair key2 = readPem(f.toURI().toString(), null);
    checkNonTrivial(key2);
    Assert.assertEquals(key2.getPrivate().getEncoded(), key.getPrivate().getEncoded());
    Assert.assertEquals(key2.getPublic().getEncoded(), key.getPublic().getEncoded());
}
 
Example 8
Source File: BrooklynClusterIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@BeforeMethod(alwaysRun=true)
@Override
public void setUp() throws Exception {
    super.setUp();
    pseudoBrooklynPropertiesFile = Os.newTempFile("brooklynnode-test", ".properties");
    pseudoBrooklynPropertiesFile.delete();

    pseudoBrooklynCatalogFile = Os.newTempFile("brooklynnode-test", ".catalog");
    pseudoBrooklynCatalogFile.delete();

    loc = app.newLocalhostProvisioningLocation();
    locs = ImmutableList.of(loc);
}
 
Example 9
Source File: PostgreSqlSshDriver.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public void logTailOfPostgresLog() {
    try {
        File file = Os.newTempFile("postgresql-"+getEntity().getId(), "log");
        int result = getMachine().copyFrom(getLogFile(), file.getAbsolutePath());
        if (result != 0) throw new IllegalStateException("Could not access log file " + getLogFile());
        log.info("Saving {} contents as {}", getLogFile(), file);
        Streams.logStreamTail(log, "postgresql.log", Streams.byteArrayOfString(Files.toString(file, Charsets.UTF_8)), 1024);
        file.delete();
    } catch (IOException ioe) {
        log.debug("Error reading copied log file: {}", ioe);
    }
}
 
Example 10
Source File: BundleAndTypeResourcesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidArchive() throws Exception {
    File f = Os.newTempFile("osgi", "zip");

    Response response = client().path("/catalog/bundles")
            .header(HttpHeaders.CONTENT_TYPE, "application/x-zip")
            .post(Streams.readFully(new FileInputStream(f)));

    assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
    Asserts.assertStringContainsIgnoreCase(response.readEntity(String.class), "zip file is empty");
}
 
Example 11
Source File: SshMachineLocationIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups = "Integration")
public void testCopyFileTo() throws Exception {
    File dest = Os.newTempFile(getClass(), ".dest.tmp");
    File src = Os.newTempFile(getClass(), ".src.tmp");
    try {
        Files.write("abc", src, Charsets.UTF_8);
        host.copyTo(src, dest);
        assertEquals("abc", Files.readFirstLine(dest, Charsets.UTF_8));
    } finally {
        src.delete();
        dest.delete();
    }
}
 
Example 12
Source File: FileBasedStoreObjectAccessorWriterTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")
public void testPutCreatesNewFile() throws Exception {
    File nonExistantFile = Os.newTempFile(getClass(), "txt");
    nonExistantFile.delete();
    StoreObjectAccessorLocking accessor = new StoreObjectAccessorLocking(new FileBasedStoreObjectAccessor(nonExistantFile, ".tmp"));
    try {
        accessor.put("abc");
        assertEquals(Files.readLines(nonExistantFile, Charsets.UTF_8), ImmutableList.of("abc"));
    } finally {
        accessor.delete();
    }
}
 
Example 13
Source File: BashCommandsIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    super.setUp();
    
    exec = new BasicExecutionContext(mgmt.getExecutionManager());
    
    destFile = Os.newTempFile(getClass(), "commoncommands-test-dest.txt");
    
    sourceNonExistantFile = new File("/this/does/not/exist/ERQBETJJIG1234");
    sourceNonExistantFileUrl = sourceNonExistantFile.toURI().toString();
    
    sourceFile1 = Os.newTempFile(getClass(), "commoncommands-test.txt");
    sourceFileUrl1 = sourceFile1.toURI().toString();
    Files.write("mysource1".getBytes(), sourceFile1);
    
    sourceFile2 = Os.newTempFile(getClass(), "commoncommands-test2.txt");
    sourceFileUrl2 = sourceFile2.toURI().toString();
    Files.write("mysource2".getBytes(), sourceFile2);

    localRepoEntityVersionPath = JavaClassNames.simpleClassName(this)+"-test-dest-"+Identifiers.makeRandomId(8);
    localRepoBasePath = new File(format("%s/.brooklyn/repository", System.getProperty("user.home")));
    localRepoEntityBasePath = new File(localRepoBasePath, localRepoEntityVersionPath);
    localRepoEntityFile = new File(localRepoEntityBasePath, localRepoFilename);
    localRepoEntityBasePath.mkdirs();
    Files.write("mylocal1".getBytes(), localRepoEntityFile);

    tmpSudoersFile = Os.newTempFile(getClass(), "sudoers" + Identifiers.makeRandomId(8));

    String sudoers = ResourceUtils.create(this).getResourceAsString("classpath://brooklyn/util/ssh/test_sudoers");
    Files.write(sudoers.getBytes(), tmpSudoersFile);
    
    loc = mgmt.getLocationManager().createLocation(LocalhostMachineProvisioningLocation.spec()).obtain();
}
 
Example 14
Source File: CatalogResourceTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test
public void testOsgiBundleWithBom() throws Exception {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    final String bundleSymbolicName = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_SYMBOLIC_NAME_FULL;
    final String version = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_VERSION;
    final String bundleUrl = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL;
    final String itemSymbolicName = "my-entity";
    BundleMaker bm = new BundleMaker(manager);
    File f = Os.newTempFile("osgi", "jar");
    Files.copyFile(ResourceUtils.create(this).getResourceFromUrl(bundleUrl), f);
    
    String bom = Joiner.on("\n").join(
            "brooklyn.catalog:",
            "  bundle: " + bundleSymbolicName,
            "  version: " + version,
            "  id: " + itemSymbolicName,
            "  itemType: entity",
            "  name: My Catalog App",
            "  description: My description",
            "  icon_url: classpath:/org/apache/brooklyn/test/osgi/entities/icon.gif",
            "  item:",
            "    type: org.apache.brooklyn.core.test.entity.TestEntity");
    
    f = bm.copyAdding(f, MutableMap.of(new ZipEntry("catalog.bom"), (InputStream) new ByteArrayInputStream(bom.getBytes())));

    Response response = client().path("/catalog")
            .header(HttpHeaders.CONTENT_TYPE, "application/x-jar")
            .post(Streams.readFully(new FileInputStream(f)));

    assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());

    CatalogSummaryAsserts.newInstance(CatalogItemType.ENTITY, itemSymbolicName, version)
            .planYamlPredicate(StringPredicates.containsLiteral("org.apache.brooklyn.core.test.entity.TestEntity"))
            .name("My Catalog App")
            .description("My description")
            .expectedInterfaces(Reflections.getAllInterfaces(TestEntity.class))
            .iconData((data) -> {assertEquals(data.length, 43); return true;})
            .applyAsserts(() -> client());
    
    RegisteredTypeAsserts.newInstance(itemSymbolicName, version)
            .libraryNames(new VersionedName(bundleSymbolicName, version))
            .libraryUrls((String)null)
            .iconUrl("classpath:/org/apache/brooklyn/test/osgi/entities/icon.gif")
            .applyAsserts(getManagementContext().getTypeRegistry());
}
 
Example 15
Source File: CatalogResourceTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test
public void testOsgiBundleWithBomNotInBrooklynNamespace() throws Exception {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_PATH);
    final String bundleSymbolicName = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_SYMBOLIC_NAME_FULL;
    final String version = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_VERSION;
    final String bundleUrl = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_URL;
    final String entityType = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_ENTITY;
    final String iconPath = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_ICON_PATH;
    final String itemSymbolicName = "my-item";
    BundleMaker bm = new BundleMaker(manager);
    File f = Os.newTempFile("osgi", "jar");
    Files.copyFile(ResourceUtils.create(this).getResourceFromUrl(bundleUrl), f);

    String bom = Joiner.on("\n").join(
            "brooklyn.catalog:",
            "  bundle: " + bundleSymbolicName,
            "  version: " + version,
            "  id: " + itemSymbolicName,
            "  itemType: entity",
            "  name: My Catalog App",
            "  description: My description",
            "  icon_url: classpath:" + iconPath,
            "  item:",
            "    type: " + entityType);

    f = bm.copyAdding(f, MutableMap.of(new ZipEntry("catalog.bom"), (InputStream) new ByteArrayInputStream(bom.getBytes())));

    Response response = client().path("/catalog")
            .header(HttpHeaders.CONTENT_TYPE, "application/x-zip")
            .post(Streams.readFully(new FileInputStream(f)));


    assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());

    CatalogSummaryAsserts.newInstance(CatalogItemType.ENTITY, itemSymbolicName, version)
            .planYamlPredicate(StringPredicates.containsLiteral(entityType))
            .name("My Catalog App")
            .description("My description")
            .expectedInterfaces(ImmutableList.of(Entity.class, BrooklynObject.class, Identifiable.class, Configurable.class))
            .iconData((data) -> {assertEquals(data.length, 43); return true;})
            .applyAsserts(() -> client());
    
    RegisteredTypeAsserts.newInstance(itemSymbolicName, version)
            .libraryNames(new VersionedName(bundleSymbolicName, version))
            .libraryUrls((String)null)
            .iconUrl("classpath:"+iconPath)
            .applyAsserts(getManagementContext().getTypeRegistry());

    // Check that the catalog item is useable (i.e. can deploy the entity)
    String appYaml = Joiner.on("\n").join(
            "services:",
            "- type: " + itemSymbolicName + ":" + version,
            "  name: myEntityName");

    Response appResponse = client().path("/applications")
            .header(HttpHeaders.CONTENT_TYPE, "application/x-yaml")
            .post(appYaml);

    assertEquals(appResponse.getStatus(), Response.Status.CREATED.getStatusCode());

    Entity entity = Iterables.tryFind(getManagementContext().getEntityManager().getEntities(), EntityPredicates.displayNameEqualTo("myEntityName")).get();
    assertEquals(entity.getEntityType().getName(), entityType);
}
 
Example 16
Source File: ConfigInheritanceYamlTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@BeforeMethod(alwaysRun = true)
@Override
public void setUp() throws Exception {
    super.setUp();
    
    executor = Executors.newCachedThreadPool();
    
    emptyFile = Os.newTempFile("ConfigInheritanceYamlTest", ".txt");
    emptyFile2 = Os.newTempFile("ConfigInheritanceYamlTest2", ".txt");
    emptyFile3 = Os.newTempFile("ConfigInheritanceYamlTest3", ".txt");
    
    addCatalogItems(
            "brooklyn.catalog:",
            "  id: EmptySoftwareProcess-with-conf",
            "  itemType: entity",
            "  item:",
            "    type: org.apache.brooklyn.entity.software.base.EmptySoftwareProcess",
            "    brooklyn.config:",
            "      shell.env:",
            "        ENV1: myEnv1",
            "      templates.preinstall:",
            "        "+emptyFile.getAbsolutePath()+": myfile",
            "      files.preinstall:",
            "        "+emptyFile.getAbsolutePath()+": myfile",
            "      templates.install:",
            "        "+emptyFile.getAbsolutePath()+": myfile",
            "      files.install:",
            "        "+emptyFile.getAbsolutePath()+": myfile",
            "      templates.runtime:",
            "        "+emptyFile.getAbsolutePath()+": myfile",
            "      files.runtime:",
            "        "+emptyFile.getAbsolutePath()+": myfile",
            "      provisioning.properties:",
            "        mykey: myval",
            "        templateOptions:",
            "          myOptionsKey: myOptionsVal");
    
    addCatalogItems(
            "brooklyn.catalog:",
            "  id: EmptySoftwareProcess-with-env",
            "  itemType: entity",
            "  item:",
            "    type: org.apache.brooklyn.entity.software.base.EmptySoftwareProcess",
            "    brooklyn.config:",
            "      env:",
            "        ENV1: myEnv1");
    
    addCatalogItems(
            "brooklyn.catalog:",
            "  id: EmptySoftwareProcess-with-shell.env",
            "  itemType: entity",
            "  item:",
            "    type: org.apache.brooklyn.entity.software.base.EmptySoftwareProcess",
            "    brooklyn.config:",
            "      shell.env:",
            "        ENV1: myEnv1");

    addCatalogItems(
            "brooklyn.catalog:",
            "  id: localhost-stub",
            "  itemType: location",
            "  name: Localhost (stubbed-SSH)",
            "  item:",
            "    type: localhost",
            "    brooklyn.config:",
            "      sshToolClass: "+RecordingSshTool.class.getName());
}
 
Example 17
Source File: BundleAndTypeResourcesTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test
public void testOsgiBundleWithBom() throws Exception {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    final String symbolicName = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_SYMBOLIC_NAME_FULL;
    final String version = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_VERSION;
    final String bundleUrl = OsgiStandaloneTest.BROOKLYN_TEST_OSGI_ENTITIES_URL;
    BundleMaker bm = new BundleMaker(manager);
    File f = Os.newTempFile("osgi", "jar");
    Files.copyFile(ResourceUtils.create(this).getResourceFromUrl(bundleUrl), f);
    
    String bom = Joiner.on("\n").join(
            "brooklyn.catalog:",
            "  bundle: " + symbolicName,
            "  version: " + version,
            "  id: " + symbolicName,
            "  itemType: entity",
            "  name: My Catalog App",
            "  description: My description",
            "  icon_url: classpath:/org/apache/brooklyn/test/osgi/entities/icon.gif",
            "  item:",
            "    type: org.apache.brooklyn.core.test.entity.TestEntity");
    
    f = bm.copyAdding(f, MutableMap.of(new ZipEntry("catalog.bom"), (InputStream) new ByteArrayInputStream(bom.getBytes())));

    Response response = client().path("/catalog/bundles")
            .header(HttpHeaders.CONTENT_TYPE, "application/x-jar")
            .post(Streams.readFully(new FileInputStream(f)));
    
    assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());

    TypeDetail entityItem = client().path("/catalog/types/"+symbolicName + "/" + version)
            .get(TypeDetail.class);
    assertEquals(entityItem.getSymbolicName(), symbolicName);
    assertEquals(entityItem.getVersion(), version);

    // assert we can cast it as summary
    TypeSummary entityItemSummary = client().path("/catalog/types/"+symbolicName + "/" + version)
        .get(TypeSummary.class);
    assertEquals(entityItemSummary.getSymbolicName(), symbolicName);
    assertEquals(entityItemSummary.getVersion(), version);

    List<TypeSummary> typesInBundle = client().path("/catalog/bundles/" + symbolicName + "/" + version + "/types")
        .get(new GenericType<List<TypeSummary>>() {});
    assertEquals(Iterables.getOnlyElement(typesInBundle), entityItemSummary);

    TypeDetail entityItemFromBundle = client().path("/catalog/bundles/" + symbolicName + "/" + version + "/types/" + symbolicName + "/" + version)
        .get(TypeDetail.class);
    assertEquals(entityItemFromBundle, entityItem);
    
    // and internally let's check we have libraries
    RegisteredType item = getManagementContext().getTypeRegistry().get(symbolicName, version);
    Assert.assertNotNull(item);
    Collection<OsgiBundleWithUrl> libs = item.getLibraries();
    assertEquals(libs.size(), 1);
    OsgiBundleWithUrl lib = Iterables.getOnlyElement(libs);
    Assert.assertNull(lib.getUrl());

    assertEquals(lib.getSymbolicName(), "org.apache.brooklyn.test.resources.osgi.brooklyn-test-osgi-entities");
    assertEquals(lib.getSuppliedVersionString(), version);

    // now let's check other things on the item
    URI expectedIconUrl = URI.create(getEndpointAddress() + "/catalog/types/" + symbolicName + "/" + entityItem.getVersion()+"/icon").normalize();
    assertEquals(entityItem.getDisplayName(), "My Catalog App");
    assertEquals(entityItem.getDescription(), "My description");
    assertEquals(entityItem.getIconUrl(), expectedIconUrl.getPath());
    assertEquals(item.getIconUrl(), "classpath:/org/apache/brooklyn/test/osgi/entities/icon.gif");

    if (checkTraits(false)) {
        // an InterfacesTag should be created for every catalog item
        @SuppressWarnings("unchecked")
        Map<String, List<String>> traitsMapTag = Iterables.getOnlyElement(Iterables.filter(entityItem.getTags(), Map.class));
        List<String> actualInterfaces = traitsMapTag.get("traits");
        List<Class<?>> expectedInterfaces = Reflections.getAllInterfaces(TestEntity.class);
        assertEquals(actualInterfaces.size(), expectedInterfaces.size());
        for (Class<?> expectedInterface : expectedInterfaces) {
            assertTrue(actualInterfaces.contains(expectedInterface.getName()));
        }
    }

    byte[] iconData = client().path("/catalog/types/" + symbolicName + "/" + version + "/icon").get(byte[].class);
    assertEquals(iconData.length, 43);
}
 
Example 18
Source File: BundleAndTypeResourcesTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test
public void testOsgiBundleWithBomNotInBrooklynNamespace() throws Exception {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_PATH);
    final String symbolicName = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_SYMBOLIC_NAME_FULL;
    final String version = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_VERSION;
    final String bundleUrl = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_URL;
    final String entityType = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_ENTITY;
    final String iconPath = OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_COM_EXAMPLE_ICON_PATH;
    BundleMaker bm = new BundleMaker(manager);
    File f = Os.newTempFile("osgi", "jar");
    Files.copyFile(ResourceUtils.create(this).getResourceFromUrl(bundleUrl), f);

    String bom = Joiner.on("\n").join(
            "brooklyn.catalog:",
            "  bundle: " + symbolicName,
            "  version: " + version,
            "  id: " + symbolicName,
            "  itemType: entity",
            "  name: My Catalog App",
            "  description: My description",
            "  icon_url: classpath:" + iconPath,
            "  item:",
            "    type: " + entityType);

    f = bm.copyAdding(f, MutableMap.of(new ZipEntry("catalog.bom"), (InputStream) new ByteArrayInputStream(bom.getBytes())));

    Response response = client().path("/catalog/bundles")
            .header(HttpHeaders.CONTENT_TYPE, "application/x-zip")
            .post(Streams.readFully(new FileInputStream(f)));


    assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode());

    TypeDetail entityItem = client().path("/catalog/types/"+symbolicName + "/" + version)
            .get(TypeDetail.class);

    Assert.assertNotNull(entityItem.getPlan().getData());
    Assert.assertTrue(entityItem.getPlan().getData().toString().contains(entityType));

    assertEquals(entityItem.getSymbolicName(), symbolicName);
    assertEquals(entityItem.getVersion(), version);

    // and internally let's check we have libraries
    RegisteredType item = getManagementContext().getTypeRegistry().get(symbolicName, version);
    Assert.assertNotNull(item);
    Collection<OsgiBundleWithUrl> libs = item.getLibraries();
    assertEquals(libs.size(), 1);
    OsgiBundleWithUrl lib = Iterables.getOnlyElement(libs);
    Assert.assertNull(lib.getUrl());

    assertEquals(lib.getSymbolicName(), symbolicName);
    assertEquals(lib.getSuppliedVersionString(), version);

    // now let's check other things on the item
    assertEquals(entityItem.getDescription(), "My description");
    URI expectedIconUrl = URI.create(getEndpointAddress() + "/catalog/types/" + symbolicName + "/" + entityItem.getVersion() + "/icon").normalize();
    assertEquals(entityItem.getIconUrl(), expectedIconUrl.getPath());
    assertEquals(item.getIconUrl(), "classpath:" + iconPath);

    if (checkTraits(false)) {
        // an InterfacesTag should be created for every catalog item
        @SuppressWarnings("unchecked")
        Map<String, List<String>> traitsMapTag = Iterables.getOnlyElement(Iterables.filter(entityItem.getTags(), Map.class));
        List<String> actualInterfaces = traitsMapTag.get("traits");
        List<String> expectedInterfaces = ImmutableList.of(Entity.class.getName(), BrooklynObject.class.getName(), Identifiable.class.getName(), Configurable.class.getName());
        assertTrue(actualInterfaces.containsAll(expectedInterfaces), "actual="+actualInterfaces);
    }

    byte[] iconData = client().path("/catalog/types/" + symbolicName + "/" + version + "/icon").get(byte[].class);
    assertEquals(iconData.length, 43);

    // Check that the catalog item is useable (i.e. can deploy the entity)
    String appYaml = Joiner.on("\n").join(
            "services:",
            "- type: " + symbolicName + ":" + version,
            "  name: myEntityName");

    Response appResponse = client().path("/applications")
            .header(HttpHeaders.CONTENT_TYPE, "application/x-yaml")
            .post(appYaml);

    assertEquals(appResponse.getStatus(), Response.Status.CREATED.getStatusCode());

    Entity entity = Iterables.tryFind(getManagementContext().getEntityManager().getEntities(), EntityPredicates.displayNameEqualTo("myEntityName")).get();
    assertEquals(entity.getEntityType().getName(), entityType);
}
 
Example 19
Source File: ArchiveUtilsTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@BeforeClass(alwaysRun=true)
public void setUpClass() throws Exception {
    origZip = newZip(archiveContents);
    origJar = Os.newTempFile(ArchiveUtilsTest.class, ".jar");
    Files.copy(origZip, origJar);
}
 
Example 20
Source File: FileBasedStoreObjectAccessorWriterTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
protected StoreObjectAccessorWithLock newPersistenceStoreObjectAccessor() throws IOException {
    file = Os.newTempFile(getClass(), "txt");
    return new StoreObjectAccessorLocking(new FileBasedStoreObjectAccessor(file, ".tmp"));
}