/** * Creates a {@link ResourceUtils} object with the given context. * <p> * Uses the {@link ClassLoader} of the given {@code contextObject} for class * loading and the {@code contextMessage} string for error messages. * * @see ResourceUtils#create(ClassLoader, Object, String) * @see ResourceUtils#create(Object) */ public static final ResourceUtils create(Object contextObject, String contextMessage) { return new ResourceUtils(contextObject, contextMessage); }
/** * Creates a {@link ResourceUtils} object with itself as the context. * * @see ResourceUtils#create(Object) */ public static final ResourceUtils create() { return new ResourceUtils(null); }
@VisibleForTesting static List<String> getIpAddressWebsites() { String file = new ResourceUtils(LocalhostExternalIpLoader.class) .getResourceAsString("classpath://org/apache/brooklyn/location/geo/external-ip-address-resolvers.txt"); Iterable<String> lines = Splitter.on('\n') .omitEmptyStrings() .trimResults() .split(file); List<String> urls = Lists.newArrayList(Iterables.filter(lines, Predicates.not(StringPredicates.startsWith("#")))); Collections.shuffle(urls); return urls; }
@Override public boolean apply(@Nullable String resource, @Nullable BrooklynObject context) { return !Strings.isBlank(resource) && new ResourceUtils(context).doesUrlExist(resource); }
@SuppressWarnings("unchecked") public static Iterable<String> getDefaultTypes() { String input = new ResourceUtils(null).getResourceAsString(CONFIG_URL); return (List) Yamls.getAt(input, ImmutableList.of("defaultTypes")); }
protected String getScript(ImplementationArtifact artifact) { // Trying to get the CSAR file based on the artifact reference. If it fails, then we try to get the // content of the script from any resources String artifactRef = artifact.getArtifactRef(); Optional<Path> csarPath = getCsarPath(artifact.getArchiveName(), artifact.getArchiveVersion()); if(!csarPath.isPresent()) { return new ResourceUtils(this).getResourceAsString(artifactRef); } return new ResourceUtils(this).getResourceAsString(csarPath.get().getParent().toString() + expandedFolder + artifactRef); }
private void populateInitialFromUri(BasicBrooklynCatalog catalog, String catalogUrl) { log.debug("Loading initial catalog from {}", catalogUrl); try { String contents = new ResourceUtils(this).getResourceAsString(catalogUrl); catalog.reset(MutableList.<CatalogItem<?,?>>of()); Object result = catalog.addItems(contents); log.debug("Loaded initial catalog from {}: {}", catalogUrl, result); } catch (Exception e) { Exceptions.propagateIfFatal(e); log.warn("Error importing catalog from " + catalogUrl + ": " + e, e); } }
@Override public void run() { String fileContents = new ResourceUtils(this).getResourceAsString(filePath); Assert.assertTrue(fileContents.contains("checkRunning")); } });
protected Reader loadYaml(String url, String location) { String yaml = "location: "+location+"\n"+ new ResourceUtils(this).getResourceAsString(url); return new StringReader(yaml); }
@Override public void run() { String fileContents = new ResourceUtils(this).getResourceAsString(filePath); Assert.assertTrue(fileContents.contains("stop")); } });
@Test(groups={"Integration"}) public void testResourceFromUrlFollowsRedirect() throws Exception { String contents = new ResourceUtils(this).getResourceAsString("http://bit.ly/brooklyn-visitors-creation-script"); assertFalse(contents.contains("bit.ly"), "contents="+contents); }
protected Reader loadYaml(String yamlFileName, String ...extraLines) throws Exception { String input = new ResourceUtils(this).getResourceAsString(yamlFileName).trim(); StringBuilder builder = new StringBuilder(input); for (String l: extraLines) builder.append("\n").append(l); return new StringReader(builder.toString()); }
/** returns the creation script contents, if it exists, or null if none is defined (error if it cannot be loaded) */ @Nullable public static String getDatabaseCreationScriptAsString(Entity entity) { String url = entity.getConfig(DatastoreMixins.CREATION_SCRIPT_URL); if (!Strings.isBlank(url)) return new ResourceUtils(entity).getResourceAsString(url); String templateUrl = entity.getConfig(DatastoreMixins.CREATION_SCRIPT_TEMPLATE); if (!Strings.isBlank(templateUrl)) return TemplateProcessor.processTemplateContents(new ResourceUtils(entity).getResourceAsString(templateUrl), (EntityInternal) entity, ImmutableMap.<String, Object>of()); String contents = entity.getConfig(DatastoreMixins.CREATION_SCRIPT_CONTENTS); if (!Strings.isBlank(contents)) return contents; return null; }
@Nullable private static String getDatabaseCreationScriptAsString(Entity entity) { String url = entity.getConfig(MySqlMaster.MASTER_CREATION_SCRIPT_URL); if (!Strings.isBlank(url)) return new ResourceUtils(entity).getResourceAsString(url); String contents = entity.getConfig(MySqlMaster.MASTER_CREATION_SCRIPT_CONTENTS); if (!Strings.isBlank(contents)) return contents; return null; } }
@Test public void testBigIntegerFormattedCorrectly() { Map<String, Object> substitutions = ImmutableMap.<String, Object>builder() .put("entity", new MockInputForTemplate()) .put("driver", new MockInputForTemplate()) .build(); String templatedUrl = CassandraNode.CASSANDRA_CONFIG_TEMPLATE_URL.getDefaultValue(); String url = TemplateProcessor.processTemplateContents(templatedUrl, ImmutableMap.of("entity", ImmutableMap.of("majorMinorVersion", "1.2"))); String templateContents = new ResourceUtils(this).getResourceAsString(url); String processedTemplate = TemplateProcessor.processTemplateContents(templateContents, substitutions); Assert.assertEquals(processedTemplate.indexOf("775,808"), -1); Assert.assertTrue(processedTemplate.indexOf("-9223372036854775808") > 0); }
@Test public void testLoadResourceFromBundle() throws Exception { String id = "resource.test"; addCatalogOSGiEntity(id, SIMPLE_ENTITY_TYPE); String yaml = "services: \n" + " - serviceType: "+ver(id); Entity app = createAndStartApplication(yaml); Entity simpleEntity = Iterables.getOnlyElement(app.getChildren()); InputStream icon = new ResourceUtils(simpleEntity).getResourceFromUrl("classpath:/org/apache/brooklyn/test/osgi/entities/icon.gif"); assertTrue(icon != null); icon.close(); }
@Test(groups = "Integration") public void testTemplatesAndCopiesAllFilesInDirectory() throws IOException { localhost.config().set(BrooklynConfigKeys.ONBOX_BASE_DIR, tempDataDir.getAbsolutePath()); Path templatePath = Paths.get(tempDataDir.getAbsolutePath(), "runtime-templates", "template.yaml"); Files.createParentDirs(templatePath.toFile()); String templateContent = new ResourceUtils(null).getResourceAsString("classpath://org/apache/brooklyn/entity/software/base/template.yaml"); Files.write(templateContent.getBytes(), templatePath.toFile()); EmptySoftwareProcess entity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class) .configure(SoftwareProcess.RUNTIME_TEMPLATES, MutableMap.of(templatePath.getParent().toString(), "custom-runtime-templates"))); app.start(ImmutableList.of(localhost)); File runtimeTemplate = new File(entity.getAttribute(SoftwareProcess.RUN_DIR), "custom-runtime-templates/template.yaml"); assertTemplateValues(runtimeTemplate); }
private Long getRunTimeUtc(VanillaSoftwareProcess p) { Assert.assertNotNull(p.getAttribute(SoftwareProcess.RUN_DIR)); return Long.parseLong( Strings.getFirstWordAfter(new ResourceUtils(this).getResourceAsString(Os.mergePaths(p.getAttribute(SoftwareProcess.RUN_DIR), "DATE")), "utc") ); }
private synchronized void loadTheDefaultCatalog(boolean lookOnDiskForDefaultCatalog) { if (defaultCatalog!=null) return; BrooklynProperties props = BrooklynProperties.Factory.newEmpty(); props.put(BrooklynServerConfig.BROOKLYN_CATALOG_URL.getName(), // if default catalog is picked up from the system, we might get random stuff from ~/.brooklyn/ instead of the default; // useful as an integration check that we default correctly, but irritating for people to use if they have such a catalog installed (lookOnDiskForDefaultCatalog ? "" : "data:,"+Urls.encode(new ResourceUtils(this).getResourceAsString("classpath:/brooklyn/default.catalog.bom")))); LocalManagementContext mgmt = newManagementContext(props); defaultCatalog = mgmt.getCatalog(); log.info("ENTITIES loaded for DEFAULT: "+defaultCatalog.getCatalogItems(Predicates.alwaysTrue())); }
@Test(groups={"Integration", "WIP", "Broken"}) public void testJavaWebWithMemberSpecRebind() throws Exception { Reader input = Streams.reader(new ResourceUtils(this).getResourceFromUrl("test-java-web-app-spec-and-db-with-function.yaml")); AssemblyTemplate at = platform.pdp().registerDeploymentPlan(input); Assembly assembly = at.getInstantiator().newInstance().instantiate(at, platform); final Application app = (Application) mgmt().getEntityManager().getEntity(assembly.getId()); Set<Task<?>> tasks = BrooklynTaskTags.getTasksInEntityContext(mgmt().getExecutionManager(), app); for (Task<?> t: tasks) t.blockUntilEnded(); Entities.dumpInfo(app); Application app2 = rebind(app); Assert.assertEquals(app2.getChildren().size(), 2); }