org.apache.brooklyn.util.text.Strings Java Examples

The following examples show how to use org.apache.brooklyn.util.text.Strings. 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: SshCommandSensor.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Beta
public static String makeCommandExecutingInDirectory(String command, String executionDir, Entity entity) {
    String finalCommand = command;
    String execDir = executionDir;
    if (Strings.isBlank(execDir)) {
        // default to run dir
        execDir = (entity != null) ? entity.getAttribute(BrooklynConfigKeys.RUN_DIR) : null;
        // if no run dir, default to home
        if (Strings.isBlank(execDir)) {
            execDir = "~";
        }
    } else if (!Os.isAbsolutish(execDir)) {
        // relative paths taken wrt run dir
        String runDir = (entity != null) ? entity.getAttribute(BrooklynConfigKeys.RUN_DIR) : null;
        if (!Strings.isBlank(runDir)) {
            execDir = Os.mergePaths(runDir, execDir);
        }
    }
    if (!"~".equals(execDir)) {
        finalCommand = "mkdir -p '"+execDir+"' && cd '"+execDir+"' && "+finalCommand;
    }
    return finalCommand;
}
 
Example #2
Source File: CouchDBNodeLiveTest.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Test(groups = "Live", dataProvider = "virtualMachineData")
protected void testOperatingSystemProvider(String imageId, String provider, String region, String description) throws Exception {
    log.info("Testing CouchDB on {}{} using {} ({})", new Object[] { provider, Strings.isNonEmpty(region) ? ":" + region : "", description, imageId });

    Map<String, String> properties = MutableMap.of("imageId", imageId);
    Location testLocation = app.getManagementContext().getLocationRegistry()
            .getLocationManaged(provider + (Strings.isNonEmpty(region) ? ":" + region : ""), properties);

    CouchDBNode couchdb = app.createAndManageChild(EntitySpec.create(CouchDBNode.class)
            .configure("httpPort", "12345+")
            .configure("clusterName", "TestCluster"));
    app.start(ImmutableList.of(testLocation));
    EntityAsserts.assertAttributeEqualsEventually(couchdb, Startable.SERVICE_UP, true);

    JcouchdbSupport jcouchdb = new JcouchdbSupport(couchdb);
    jcouchdb.jcouchdbTest();
}
 
Example #3
Source File: OsgiLauncherImpl.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public OsgiLauncherImpl startPartOne() {
    // make sure brooklyn-core bundle is started
    brooklynVersion.getVersion();

    Configuration brooklynConfig = getConfiguration(configAdmin, BROOKLYN_CONFIG_PID);
    // Note that this doesn't check whether the files exist, just that there are potential alternative sources for configuration.
    if (brooklynConfig == null && Strings.isEmpty(globalBrooklynProperties) && Strings.isEmpty(localBrooklynProperties)) {
        LOG.warn("Config Admin PID '" + BROOKLYN_CONFIG_PID + "' not found, not using external configuration. Create a brooklyn.cfg file in etc folder.");
    }
    configSupplier = new ConfigSupplier(brooklynConfig);
    BrooklynPropertiesFactoryHelper helper = new BrooklynPropertiesFactoryHelper(
            globalBrooklynProperties, localBrooklynProperties, configSupplier);
    setBrooklynPropertiesBuilder(helper.createPropertiesBuilder());
    return super.startPartOne();
}
 
Example #4
Source File: LocationConfigUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public static Map<ConfigKey<String>,String> finalAndOriginalSpecs(String finalSpec, Object ...sourcesForOriginalSpec) {
    // yuck!: TODO should clean up how these things get passed around
    Map<ConfigKey<String>,String> result = MutableMap.of();
    if (finalSpec!=null) 
        result.put(LocationInternal.FINAL_SPEC, finalSpec);
    
    String originalSpec = null;
    for (Object source: sourcesForOriginalSpec) {
        if (source instanceof CharSequence) originalSpec = source.toString();
        else if (source instanceof Map) {
            if (originalSpec==null) originalSpec = Strings.toString( ((Map<?,?>)source).get(LocationInternal.ORIGINAL_SPEC) );
            if (originalSpec==null) originalSpec = Strings.toString( ((Map<?,?>)source).get(LocationInternal.ORIGINAL_SPEC.getName()) );
        }
        if (originalSpec!=null) break; 
    }
    if (originalSpec==null) originalSpec = finalSpec;
    if (originalSpec!=null)
        result.put(LocationInternal.ORIGINAL_SPEC, originalSpec);
    
    return result;
}
 
Example #5
Source File: BrooklynRestResourceUtils.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
private <T extends Entity> org.apache.brooklyn.api.entity.EntitySpec<?> toCoreEntitySpec(Class<T> clazz, String name, Map<String,String> configO, String catalogItemId) {
    Map<String, String> config = (configO == null) ? Maps.<String,String>newLinkedHashMap() : Maps.newLinkedHashMap(configO);
    
    org.apache.brooklyn.api.entity.EntitySpec<? extends Entity> result;
    if (clazz.isInterface()) {
        result = org.apache.brooklyn.api.entity.EntitySpec.create(clazz);
    } else {
        // If this is a concrete class, particularly for an Application class, we want the proxy
        // to expose all interfaces it implements.
        Class interfaceclazz = (Application.class.isAssignableFrom(clazz)) ? Application.class : Entity.class;
        Set<Class<?>> additionalInterfaceClazzes = Reflections.getInterfacesIncludingClassAncestors(clazz);
        result = org.apache.brooklyn.api.entity.EntitySpec.create(interfaceclazz).impl(clazz).additionalInterfaces(additionalInterfaceClazzes);
    }
    
    result.catalogItemId(catalogItemId);
    if (!Strings.isEmpty(name)) result.displayName(name);
    result.configure( convertFlagsToKeys(result.getImplementation(), config) );
    return result;
}
 
Example #6
Source File: CatalogMakeOsgiBundleTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testCatalogBomLoadsFileInBundle() throws Exception {
    bm.setDefaultClassForLoading(getClass());
    File jf = bm.createJarFromClasspathDir("osgi/catalog-bundle-1");
    
    // add a file in the bundle
    String customText = "Sample data "+Identifiers.makeRandomId(4);
    jf = bm.copyAdding(jf, MutableMap.of(
            new ZipEntry("sample.txt"), (InputStream) new ByteArrayInputStream(customText.getBytes())));
    
    installBundle(jf);

    String yaml = Strings.lines("name: simple-app-yaml",
            "services:",
            "- type: " + "basic1",
            "  brooklyn.initializers:",
            "  - type: "+GetFileContentsEffector.class.getName());
    Entity app = createAndStartApplication(yaml);
    Entity basic1 = Iterables.getOnlyElement( app.getChildren() );
    
    // check the file put in the bundle gets loaded without needing to do anything special
    String contents = basic1.invoke(GetFileContentsEffector.GET_FILE_CONTENTS, MutableMap.of(GetFileContentsEffector.FILENAME.getName(), "classpath://sample.txt")).get();
    Asserts.assertEquals(contents, customText);
}
 
Example #7
Source File: DatastoreMixins.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
/** returns the creation script contents, if it exists, or null if none is defined (error if it cannot be loaded) */
@Nullable public static InputStream getDatabaseCreationScript(Entity entity) {
    String url = entity.getConfig(DatastoreMixins.CREATION_SCRIPT_URL);
    if (!Strings.isBlank(url))
        return new ResourceUtils(entity).getResourceFromUrl(url);

    String templateUrl = entity.getConfig(DatastoreMixins.CREATION_SCRIPT_TEMPLATE);
    if (!Strings.isBlank(templateUrl)) {
        String template = TemplateProcessor.processTemplateContents(new ResourceUtils(entity).getResourceAsString(templateUrl), (EntityInternal) entity, ImmutableMap.<String, Object>of());
        try {
            return new ByteArrayInputStream(template.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw Exceptions.propagate(e);
        }
    }

    String contents = entity.getConfig(DatastoreMixins.CREATION_SCRIPT_CONTENTS);
    if (!Strings.isBlank(contents))
        return KnownSizeInputStream.of(contents);
    return null;
}
 
Example #8
Source File: Main.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected HighAvailabilityMode computeHighAvailabilityMode(PersistMode persistMode) {
    Maybe<HighAvailabilityMode> highAvailabilityMode = Enums.valueOfIgnoreCase(HighAvailabilityMode.class, highAvailability);
    if (!highAvailabilityMode.isPresent()) {
        if (Strings.isBlank(highAvailability)) {
            throw new FatalConfigurationRuntimeException("High availability mode must not be blank");
        } else {
            throw new FatalConfigurationRuntimeException("Illegal highAvailability setting: "+highAvailability);
        }
    }
   
    if (highAvailabilityMode.get() != HighAvailabilityMode.DISABLED) {
        if (persistMode == PersistMode.DISABLED) {
            if (highAvailabilityMode.get() == HighAvailabilityMode.AUTO)
                return HighAvailabilityMode.DISABLED;
            throw new FatalConfigurationRuntimeException("Cannot specify highAvailability when persistence is disabled");
        } else if (persistMode == PersistMode.CLEAN && 
                (highAvailabilityMode.get() == HighAvailabilityMode.STANDBY 
                || highAvailabilityMode.get() == HighAvailabilityMode.HOT_STANDBY
                || highAvailabilityMode.get() == HighAvailabilityMode.HOT_BACKUP)) {
            throw new FatalConfigurationRuntimeException("Cannot specify highAvailability "+highAvailabilityMode.get()+" when persistence is CLEAN");
        }
    }
    return highAvailabilityMode.get();
}
 
Example #9
Source File: JavaSoftwareProcessSshDriver.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Answers one of "OpenJDK", "Oracle", or other vendor info.
 */
protected Optional<String> getCurrentJavaVendor() {
    // TODO Also handle IBM jvm
    log.debug("Checking Java vendor at {}@{}", getEntity(), getLocation());
    ProcessTaskWrapper<Integer> versionCommand = Entities.submit(getEntity(), SshTasks.newSshExecTaskFactory(
            getLocation(), "java -version 2>&1 | awk 'NR==2 {print $1}'"));
    versionCommand.get();
    String stdOut = versionCommand.getStdout().trim();
    if (Strings.isBlank(stdOut)) {
        log.debug("Found no Java installed at {}@{}", getEntity(), getLocation());
        return Optional.absent();
    } else if ("Java(TM)".equals(stdOut)) {
        log.debug("Found Java version at {}@{}: {}", new Object[] {getEntity(), getLocation(), stdOut});
        return Optional.of("Oracle");
    } else {
        return Optional.of(stdOut);
    }
}
 
Example #10
Source File: VanillaSoftwareYamlTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** yaml variant of VanillaSoftwareProcessAndChildrenIntegrationTest */
@Test(groups="Integration")
public void testVanillaSoftwareYamlWithChildStartedAfter() {
    SimpleYamlLauncher l = new SimpleYamlLauncherForTests();
    try {
        Application app = l.launchAppYaml("vanilla-software-with-child-blueprint.yaml");
        log.info("started "+app);

        Entity p1 = Iterables.getOnlyElement( app.getChildren() );
        Long d1 = Long.parseLong( Strings.getFirstWordAfter(new ResourceUtils(this).getResourceAsString(Os.mergePaths(p1.getAttribute(SoftwareProcess.RUN_DIR), "DATE")), "utc") );
        
        Entity p2 = Iterables.getOnlyElement( p1.getChildren() );
        Long d2 = Long.parseLong( Strings.getFirstWordAfter(new ResourceUtils(this).getResourceAsString(Os.mergePaths(p2.getAttribute(SoftwareProcess.RUN_DIR), "DATE")), "utc") );
        Assert.assertTrue( d2-d1 > 2 && d2-d1 < 10, "p2 should have started 3s after parent, but it did not ("+(d2-d1)+"s difference" );
    } finally {
        l.destroyAll();
    }
    log.info("DONE");
}
 
Example #11
Source File: SoftwareProcessEntityTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testInstallDirAndRunDirUsingTilde() throws Exception {
    String dataDirName = ".brooklyn-foo"+Strings.makeRandomId(4);
    String dataDir = "~/"+dataDirName;
    String resolvedDataDir = Os.mergePaths(Os.home(), dataDirName);
    
    MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
        .configure(BrooklynConfigKeys.ONBOX_BASE_DIR, dataDir));

    entity.start(ImmutableList.of(loc));

    Assert.assertEquals(Os.nativePath(entity.getAttribute(SoftwareProcess.INSTALL_DIR)),
                        Os.nativePath(Os.mergePaths(resolvedDataDir, "installs/MyService")));
    Assert.assertEquals(Os.nativePath(entity.getAttribute(SoftwareProcess.RUN_DIR)),
                        Os.nativePath(Os.mergePaths(resolvedDataDir, "apps/"+entity.getApplicationId()+"/entities/MyService_"+entity.getId())));
}
 
Example #12
Source File: CloudMachineNamerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateNewMachineName() {
    TestApplication app = mgmt.getEntityManager().createEntity(EntitySpec.create(TestApplication.class).displayName("TistApp"));
    TestEntity child = app.createAndManageChild(EntitySpec.create(TestEntity.class).displayName("TestEnt"));

    ConfigBag cfg = new ConfigBag()
        .configure(CloudLocationConfig.CALLER_CONTEXT, child);
    BasicCloudMachineNamer namer = new BasicCloudMachineNamer();
    
    String result = namer.generateNewMachineUniqueName(cfg);
    Assert.assertTrue(result.length() <= namer.getMaxNameLength(cfg));
    String user = Strings.maxlen(System.getProperty("user.name"), 4).toLowerCase();
    Assert.assertTrue(result.indexOf(user) >= 0);
    Assert.assertTrue(result.indexOf("-tistapp-") >= 0);
    Assert.assertTrue(result.indexOf("-testent-") >= 0);
    Assert.assertTrue(result.indexOf("-"+Strings.maxlen(app.getId(), 4).toLowerCase()) >= 0);
    Assert.assertTrue(result.indexOf("-"+Strings.maxlen(child.getId(), 4).toLowerCase()) >= 0);
}
 
Example #13
Source File: RebindClassInitializationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testRestoresSimpleApp() throws Exception {
    messages.clear();
    messages.add("creating");
    origApp.createAndManageChild(EntitySpec.create(Entity.class, MyEntityForClassInitializationTesting.class));
    messages.add("created");
    messages.add("rebinding");
    newApp = rebind();
    messages.add("rebinded");
    
    log.debug("Create and rebind message sequence is:\n- "+Strings.join(messages, "\n- "));
    Assert.assertEquals(messages, MutableList.of(
        "creating", "ME.static_initializer", "ME.initializer", 
        "WIM.static_initializer", "WIM.initializer", "WIM.constructor", 
        "ME.constructor", "created", 
        "rebinding", "ME.initializer", "WIM.initializer", "WIM.constructor", 
        "ME.constructor", "rebinded"));
}
 
Example #14
Source File: Yamls.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** Returns the original YAML with the found item replaced by the given replacement YAML.
 * @param replacement YAML to put in for the found item;
 * this YAML typically should not have any special indentation -- if required when replacing it will be inserted.
 * <p>
 * if replacing an inline map entry, the supplied entry must follow the structure being replaced;
 * for example, if replacing the value in <code>key: value</code> with a map,
 * supplying a replacement <code>subkey: value</code> would result in invalid yaml;
 * the replacement must be supplied with a newline, either before the subkey or after.
 * (if unsure we believe it is always valid to include an initial newline or comment with newline.)
 */
public String getFullYamlTextWithExtractReplaced(String replacement) {
    if (!found()) throw new IllegalStateException("Cannot perform replacement when item was not matched.");
    String result = yaml.substring(0, getStartOfThis());
    
    String[] newLines = replacement.split("\n");
    for (int i=1; i<newLines.length; i++)
        newLines[i] = Strings.makePaddedString("", getStartColumnOfThis(), "", " ") + newLines[i];
    result += Strings.lines(newLines);
    if (replacement.endsWith("\n")) result += "\n";
    
    int end = getEndOfThis();
    result += yaml.substring(end);
    
    return result;
}
 
Example #15
Source File: Winrm4jTool.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public Winrm4jTool(ConfigBag config) {
    this.bag = checkNotNull(config, "config bag");
    host = getRequiredConfig(config, PROP_HOST);
    port = config.get(PROP_PORT);
    useSecureWinrm = config.get(USE_HTTPS_WINRM);
    authenticationScheme = config.get(USE_NTLM) ? AuthSchemes.NTLM : null;
    computerName = Strings.isNonBlank(config.get(COMPUTER_NAME)) ? config.get(COMPUTER_NAME) : null;
    user = getRequiredConfig(config, PROP_USER);
    password = getRequiredConfig(config, PROP_PASSWORD);
    execTries = getRequiredConfig(config, PROP_EXEC_TRIES);
    execRetryDelay = getRequiredConfig(config, PROP_EXEC_RETRY_DELAY);
    logCredentials = getRequiredConfig(config, LOG_CREDENTIALS);
    operationTimeout = config.get(OPERATION_TIMEOUT);
    retriesOfNetworkFailures = config.get(RETRIES_OF_NETWORK_FAILURES);
    environment = config.get(ENVIRONMENT);
}
 
Example #16
Source File: SshMachineLocation.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public String resolveOnBoxDirFor(Entity entity, String unresolvedPath) {
    ProcessTaskWrapper<Integer> baseTask = SshEffectorTasks.ssh(
        BashCommands.alternatives("mkdir -p \"${BASE_DIR}\"",
            BashCommands.chain(
                BashCommands.sudo("mkdir -p \"${BASE_DIR}\""),
                BashCommands.sudo("chown "+getUser()+" \"${BASE_DIR}\""))),
        "cd ~",
        "cd ${BASE_DIR}",
        "echo BASE_DIR_RESULT':'`pwd`:BASE_DIR_RESULT")
        .environmentVariable("BASE_DIR", unresolvedPath)
        .requiringExitCodeZero()
        .summary("initializing on-box base dir "+unresolvedPath).newTask();
    DynamicTasks.queueIfPossible(baseTask).orSubmitAsync(entity);
    return Strings.getFragmentBetween(baseTask.block().getStdout(), "BASE_DIR_RESULT:", ":BASE_DIR_RESULT");
}
 
Example #17
Source File: MachineInitTasks.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected String toTruncatedString(Iterable<?> vals, int maxShown) {
    StringBuilder result = new StringBuilder("[");
    int shown = 0;
    for (Object val : (vals == null ? ImmutableList.of() : vals)) {
        if (shown != 0) {
            result.append(", ");
        }
        if (shown < maxShown) {
            result.append(Strings.toString(val));
            shown++;
        } else {
            result.append("...");
            break;
        }
    }
    result.append("]");
    return result.toString();
}
 
Example #18
Source File: ShellAbstractTool.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public ToolAbstractExecScript(Map<String,?> props) {
    this.props = props;
    this.separator = getOptionalVal(props, PROP_SEPARATOR);
    this.out = getOptionalVal(props, PROP_OUT_STREAM);
    this.err = getOptionalVal(props, PROP_ERR_STREAM);
    
    this.scriptDir = getOptionalVal(props, PROP_SCRIPT_DIR);
    this.runAsRoot = Boolean.TRUE.equals(getOptionalVal(props, PROP_RUN_AS_ROOT));
    this.authSudo = Boolean.TRUE.equals(getOptionalVal(props, PROP_AUTH_SUDO));
    this.noExtraOutput = Boolean.TRUE.equals(getOptionalVal(props, PROP_NO_EXTRA_OUTPUT));
    this.noDeleteAfterExec = Boolean.TRUE.equals(getOptionalVal(props, PROP_NO_DELETE_SCRIPT));
    this.password = getOptionalVal(props, PROP_PASSWORD);
    this.execTimeout = getOptionalVal(props, PROP_EXEC_TIMEOUT);
    
    String summary = getOptionalVal(props, PROP_SUMMARY);
    if (summary!=null) {
        summary = Strings.makeValidFilename(summary);
        if (summary.length()>30) 
            summary = summary.substring(0,30);
    }
    this.scriptNameWithoutExtension = "brooklyn-"+
            Time.makeDateStampString()+"-"+Identifiers.makeRandomId(4)+
            (Strings.isBlank(summary) ? "" : "-"+summary);
    this.scriptPath = Os.mergePathsUnix(scriptDir, scriptNameWithoutExtension+".sh");
}
 
Example #19
Source File: WindowsTestFixture.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static MachineProvisioningLocation<WinRmMachineLocation> setUpWindowsLocation(ManagementContext mgmt, Map<String, ?> props) throws Exception {
    // Commented out / unused code included here to make it easy to supply a 
    // pre-existing Windows VM for use in a bunch of different tests.
    String userPassAtHost = System.getenv(EXISTING_WINDOWS_TEST_USER_PASS_HOST_ENV_VAR);
    if (Strings.isBlank(userPassAtHost)) {
        return (MachineProvisioningLocation<WinRmMachineLocation>) newJcloudsLocation((ManagementContextInternal) mgmt, props);
    } else {
        return (MachineProvisioningLocation<WinRmMachineLocation>) newByonLocation((ManagementContextInternal) mgmt,
            MutableMap.of(
                    "winrm", userPassAtHost.split("@")[1],
                    "password", userPassAtHost.split(":")[1].split("@")[0],
                    "user", userPassAtHost.split(":")[0]
                ));
    }
}
 
Example #20
Source File: XmlMementoSerializer.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
protected String getContextDescription(Object contextHinter) {
    List<String> entries = MutableList.of();
    
    entries.add("in");
    entries.add(lookupContext.getContextDescription());
    
    if (contextHinter instanceof ReferencingMarshallingContext)
        entries.add("at "+((ReferencingMarshallingContext)contextHinter).currentPath());
    else if (contextHinter instanceof ReferenceByXPathUnmarshaller) {
        try {
            Method m = ReferenceByXPathUnmarshaller.class.getDeclaredMethod("getCurrentReferenceKey");
            m.setAccessible(true);
            entries.add("at "+m.invoke(contextHinter));
        } catch (Exception e) {
            Exceptions.propagateIfFatal(e);
            // ignore otherwise - we just won't have the position in the file
        }
    }
    
    return Strings.join(entries, " ");
}
 
Example #21
Source File: ServerResource.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Duration parseDuration(String str, Duration defaultValue) {
    if (Strings.isEmpty(str)) {
        return defaultValue;
    } else {
        return Duration.parse(str);
    }
}
 
Example #22
Source File: LocationConfigUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private static String getKeyDataFromDataKeyOrFileKey(ConfigBag config, ConfigKey<String> dataKey, ConfigKey<String> fileKey) {
    boolean unused = config.isUnused(dataKey);
    String data = config.get(dataKey);
    if (Strings.isNonBlank(data) && !unused) {
        return data.trim();
    }
    
    String file = config.get(fileKey);
    if (groovyTruth(file)) {
        List<String> files = Arrays.asList(file.split(File.pathSeparator));
        List<String> filesTidied = tidyFilePaths(files);
        String fileData = getFileContents(filesTidied);
        if (fileData == null) {
            log.warn("Invalid file" + (files.size() > 1 ? "s" : "") + " for " + fileKey + " (given " + files + 
                    (files.equals(filesTidied) ? "" : "; converted to " + filesTidied) + ") " +
                    "may fail provisioning " + config.getDescription());
        } else if (groovyTruth(data)) {
            if (!fileData.trim().equals(data.trim()))
                log.warn(dataKey.getName()+" and "+fileKey.getName()+" both specified; preferring the former");
        } else {
            data = fileData;
            config.put(dataKey, data);
            config.get(dataKey);
        }
    }
    
    return data;
}
 
Example #23
Source File: ConfigTypeCoercionYamlTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testSshConfigFromDefault() throws Exception {
    RecordingSshTool.setCustomResponse(".*myCommand.*", new RecordingSshTool.CustomResponse(0, "myResponse", null));
    
    String bp = loadYaml("config-type-coercion-test.yaml",
        "location:",
        "  localhost:",
        "    sshToolClass: "+RecordingSshTool.class.getName());
    // remove all lines referring to "exact" -- that's useful for expository and running in UI
    // but it will fail (timeout) if the port isn't available so not good in tests
    bp = Strings.removeLines(bp, StringPredicates.containsLiteralIgnoreCase("exact"));
    
    Entity app = createAndStartApplication(bp);
    waitForApplicationTasks(app);

    Map<?, ?> props = RecordingSshTool.getLastExecCmd().env;
    
    Assert.assertEquals(props.get("RANGE_PORT_SENSOR"), "20003");
    Asserts.assertStringContains((String)props.get("RANGE_PORT_CONFIG"), "{\"start\"", "20003");
    
    Assert.assertEquals(props.get("INT_PORT_CONFIG"), "20001");
    Assert.assertEquals(props.get("INT_PORT_DEFAULT_CONFIG"), "30001");
    
    Assert.assertEquals(props.get("RANGE_PORT_DEFAULT_SENSOR"), "30003");
    // NB: change in Oct 2016, default values are now coerced just like explicit value
    // (previous to Oct 2016 this would have returned just "30003+", no json)
    Asserts.assertStringContains((String)props.get("RANGE_PORT_DEFAULT_CONFIG"), "{\"start\"", "30003");
}
 
Example #24
Source File: CatalogYamlRebindTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void applyCompoundStateTransformer(RebindOptions options, final CompoundTransformer transformer) {
    options.stateTransformer(new Function<BrooklynMementoPersister, Void>() {
            @Override public Void apply(BrooklynMementoPersister input) {

                try {
                    BrooklynMementoRawData transformed = transformer.transform(input, RebindExceptionHandlerImpl.builder().build());
                    PersistenceObjectStore objectStore = ((BrooklynMementoPersisterToObjectStore)input).getObjectStore();
                    for (BrooklynObjectType type : BrooklynObjectType.values()) {
                        final List<String> contents = objectStore.listContentsWithSubPath(type.getSubPathName());
                        for (String path : contents) {
                            if (path.endsWith(".jar")) {
                                // don't apply transformers to JARs
                                continue;
                            }
                            StoreObjectAccessor accessor = objectStore.newAccessor(path);
                            String memento = checkNotNull(accessor.get(), path);
                            String replacement = transformed.getObjectsOfType(type).get(idFromPath(type, path));
                            getLogger().trace("Replacing {} with {}", memento, replacement);
                            accessor.put(replacement);
                        }
                    }
                } catch (Exception e) {
                    Exceptions.propagateIfFatal(e);
                    getLogger().warn(Strings.join(new Object[]{
                        "Caught'", e.getMessage(), "' when transforming '", input.getBackingStoreDescription()
                    }, ""), e);
                }

                return null;
            }});
}
 
Example #25
Source File: MonitorUtilsTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
private Process createDumpingProcess(boolean writeToErr) throws IOException {
    String errSuffix = writeToErr ? " >&2" : "";
    //Windows limits the length of the arguments so echo multiple times instead
    String bigstr = Strings.repeat("a", 8000);
    String bigcmd = getExecPrefix() + Strings.repeat(getSilentPrefix() + "echo " + bigstr + errSuffix + Os.LINE_SEPARATOR, 15);
    File file = Os.newTempFile("test-consume", ".bat");
    file.setExecutable(true);
    Files.write(bigcmd, file, Charsets.UTF_8);
    Process process = MonitorUtils.exec(file.getAbsolutePath());
    return process;
}
 
Example #26
Source File: TypeResource.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public List<TypeSummary> list(String supertype, String versions, String regex, String fragment) {
    List<Predicate<RegisteredType>> filters = MutableList.<Predicate<RegisteredType>>of()
        .append(RegisteredTypePredicates.entitledToSee(mgmt()));
    if (Strings.isNonBlank(supertype)) {
        // rewrite certain well known ones
        // (in future this should happen automatically as Entity.class should be known as user-friendly name 'entity') 
        if ("entity".equals(supertype)) supertype = Entity.class.getName();
        else if ("enricher".equals(supertype)) supertype = Enricher.class.getName();
        else if ("policy".equals(supertype)) supertype = Policy.class.getName();
        else if ("location".equals(supertype)) supertype = Location.class.getName();
        // TODO application probably isn't at all interesting; keep it for backward compatibility,
        // and meanwhile sort out things like "template" vs "quick launch"
        // (probably adding tags on the API)
        else if ("application".equals(supertype)) supertype = Application.class.getName();
        
        filters.add(RegisteredTypePredicates.subtypeOf(supertype));
    }
    if (TypeResource.isLatestOnly(versions, true)) {
        // TODO inefficient - does n^2 comparisons where n is sufficient
        // create RegisteredTypes.filterBestVersions to do a list after the initial parse
        // (and javadoc in predicate method below)
        filters.add(RegisteredTypePredicates.isBestVersion(mgmt()));
    }
    if (Strings.isNonEmpty(regex)) {
        filters.add(RegisteredTypePredicates.nameOrAlias(StringPredicates.containsRegex(regex)));
    }
    if (Strings.isNonEmpty(fragment)) {
        filters.add(RegisteredTypePredicates.nameOrAlias(StringPredicates.containsLiteralIgnoreCase(fragment)));
    }
    Predicate<RegisteredType> filter = Predicates.and(filters);

    ImmutableList<RegisteredType> sortedItems =
        FluentIterable.from(brooklyn().getTypeRegistry().getMatching(filter))
            .toSortedList(RegisteredTypes.RegisteredTypeNameThenBestFirstComparator.INSTANCE);
    return toTypeSummary(brooklyn(), sortedItems, ui.getBaseUriBuilder());
}
 
Example #27
Source File: PhpWebAppSoftwareProcessImpl.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private String inferCorrectAppTarballName() {
    String result;
    if (Strings.isEmpty(getConfig(APP_NAME))) {
        result = SourceNameResolver.getIdOfTarballFromUrl(getConfig(TARBALL_URL));
    } else {
        result = getConfig(APP_NAME);
    }
    return result;
}
 
Example #28
Source File: MathFunctions.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** @deprecated since 0.9.0 kept only to allow conversion of anonymous inner classes */
@SuppressWarnings("unused") @Deprecated 
private static Function<Number, String> readableStringOld(final int significantDigits, final int maxLen) {
    // TODO PERSISTENCE WORKAROUND
    return new Function<Number, String>() {
        @Override
        public String apply(@Nullable Number input) {
            if (input==null) return null;
            return Strings.makeRealString(input.doubleValue(), maxLen, significantDigits, 0);
        }
    };
}
 
Example #29
Source File: CatalogScanOsgiTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
static String bomForLegacySiblingLibraries() {
    return Strings.lines("brooklyn.catalog:",
        "    bundle: test-items",
        "    version: 2.0-test_java",
        "    items:",
        "    - scanJavaAnnotations: true",
        "      item:",
        "        id: here-item",
        "        type: "+OsgiTestResources.BROOKLYN_TEST_MORE_ENTITIES_MORE_ENTITY,
        "      libraries:",
        "      - classpath://" + OsgiTestResources.BROOKLYN_TEST_OSGI_ENTITIES_PATH,
        "      - classpath://" + OsgiTestResources.BROOKLYN_TEST_MORE_ENTITIES_V2_PATH);
}
 
Example #30
Source File: NginxTemplateConfigGenerator.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
public String generateConfigFile(NginxDriver driver, NginxController nginx) {
    // Check template URL exists
    String templateUrl = driver.getEntity().getConfig(NginxController.SERVER_CONF_TEMPLATE_URL);
    ResourceUtils.create(this).checkUrlExists(templateUrl);

    // Check SSL configuration
    ProxySslConfig ssl = driver.getEntity().getConfig(NginxController.SSL_CONFIG);
    if (ssl != null && Strings.isEmpty(ssl.getCertificateDestination()) && Strings.isEmpty(ssl.getCertificateSourceUrl())) {
        throw new IllegalStateException("ProxySslConfig can't have a null certificateDestination and null certificateSourceUrl. One or both need to be set");
    }

    // For mapping by URL
    Iterable<UrlMapping> mappings = ((NginxController) driver.getEntity()).getUrlMappings();
    Multimap<String, UrlMapping> mappingsByDomain = LinkedHashMultimap.create();
    for (UrlMapping mapping : mappings) {
        Collection<String> addrs = mapping.getAttribute(UrlMapping.TARGET_ADDRESSES);
        if (addrs != null && addrs.size() > 0) {
            mappingsByDomain.put(mapping.getDomain(), mapping);
        }
    }
    Map<String, Object> substitutions = MutableMap.<String, Object>builder()
            .putIfNotNull("ssl", ssl)
            .put("urlMappings", mappings)
            .put("domainMappings", mappingsByDomain)
            .build();

    // Get template contents and process
    String contents = ResourceUtils.create(driver.getEntity()).getResourceAsString(templateUrl);
    return TemplateProcessor.processTemplateContents(contents, driver, substitutions);
}