Java Code Examples for org.apache.brooklyn.util.text.Strings#isNonEmpty()

The following examples show how to use org.apache.brooklyn.util.text.Strings#isNonEmpty() . 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: Jetty6SshDriver.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
public void customize() {
    newScript(CUSTOMIZING)
            .body.append(
                    // create app-specific dirs
                    "mkdir logs contexts webapps",
                    // link to the binary directories; silly that we have to do this but jetty has only one notion of "jetty.home" 
                    // (jetty.run is used only for writing the pid file, not for looking up webapps or even for logging)
                    format("for x in start.jar bin contrib modules lib extras; do ln -s %s/$x $x ; done", getExpandedInstallDir()),
                    // copy config files across
                    format("for x in etc resources; do cp -r %s/$x $x ; done", getExpandedInstallDir())
                )
            .execute();


    // Copy configuration XML files across
    String destinationBrooklynConfig = Os.mergePathsUnix(getRunDir(), "etc/jetty-brooklyn.xml");
    copyTemplate("classpath://org/apache/brooklyn/entity/webapp/jetty/jetty-brooklyn.xml", destinationBrooklynConfig);
    String customConfigTemplateUrl = getConfigXmlTemplateUrl();
    if (Strings.isNonEmpty(customConfigTemplateUrl)) {
        String destinationConfigFile = Os.mergePathsUnix(getRunDir(), "etc/jetty-custom.xml");
        copyTemplate(customConfigTemplateUrl, destinationConfigFile);
    }

    getEntity().deployInitialWars();
}
 
Example 2
Source File: WindowsPerformanceCounterSensors.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(EntityLocal entity) {
    WindowsPerformanceCounterFeed.Builder builder = WindowsPerformanceCounterFeed.builder()
            .period(period)
            .entity(entity);
    for (Map<String, String> sensorConfig : sensors) {
        String name = sensorConfig.get("name");
        String sensorType = sensorConfig.get("sensorType");
        Class<?> clazz;
        try {
            clazz = Strings.isNonEmpty(sensorType)
                    ? ((EntityInternal)entity).getManagementContext().getCatalog().getRootClassLoader().loadClass(sensorType) 
                    : String.class;
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("Could not load type "+sensorType+" for sensor "+name, e);
        }
        builder.addSensor(sensorConfig.get("counter"), Sensors.newSensor(clazz, name, sensorConfig.get("description")));
    }
    entity.addFeed(builder.build());
}
 
Example 3
Source File: CatalogResource.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Deprecated
private <T,SpecT> List<CatalogItemSummary> getCatalogItemSummariesMatchingRegexFragment(
        Predicate<RegisteredType> type, String regex, String fragment, boolean allVersions) {
    List<Predicate<RegisteredType>> filters = new ArrayList();
    filters.add(type);
    if (Strings.isNonEmpty(regex))
        filters.add(RegisteredTypePredicates.stringRepresentationMatches(StringPredicates.containsRegex(regex)));
    if (Strings.isNonEmpty(fragment))
        filters.add(RegisteredTypePredicates.stringRepresentationMatches(StringPredicates.containsLiteralIgnoreCase(fragment)));
    if (!allVersions)
        filters.add(RegisteredTypePredicates.isBestVersion(mgmt()));
    
    filters.add(RegisteredTypePredicates.entitledToSee(mgmt()));

    ImmutableList<RegisteredType> sortedItems =
            FluentIterable.from(brooklyn().getTypeRegistry().getMatching(Predicates.and(filters)))
                .toSortedList(RegisteredTypes.RegisteredTypeNameThenBestFirstComparator.INSTANCE);
    return Lists.transform(sortedItems, toCatalogItemSummary(ui));
}
 
Example 4
Source File: CassandraDatacenterImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Collection<? extends Location> locations) {
    Machines.warnIfLocalhost(locations, "CassandraCluster does not support multiple nodes on localhost, " +
            "due to assumptions Cassandra makes about the use of the same port numbers used across the cluster.");

    // force this to be set - even if it is using the default
    sensors().set(CLUSTER_NAME, getConfig(CLUSTER_NAME));
    
    super.start(locations);

    connectSensors();

    // TODO wait until all nodes which we think are up are consistent 
    // i.e. all known nodes use the same schema, as reported by
    // SshEffectorTasks.ssh("echo \"describe cluster;\" | /bin/cassandra-cli");
    // once we've done that we can revert to using 2 seed nodes.
    // see CassandraCluster.DEFAULT_SEED_QUORUM
    // (also ensure the cluster is ready if we are about to run a creation script)
    Time.sleep(getConfig(DELAY_BEFORE_ADVERTISING_CLUSTER));

    String scriptUrl = getConfig(CassandraNode.CREATION_SCRIPT_URL);
    if (Strings.isNonEmpty(scriptUrl)) {
        executeScript(new ResourceUtils(this).getResourceAsString(scriptUrl));
    }

    update();
}
 
Example 5
Source File: Os.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** creates a private temp file which will be deleted on exit;
 * either prefix or ext may be null; 
 * if ext is non-empty and not > 4 chars and not starting with a ., then a dot will be inserted;
 * if either name part is too long it will be shortened to prevent filesystem errors */
public static File newTempFile(String prefix, String ext) {
    String sanitizedPrefix = (Strings.isNonEmpty(prefix) ? Strings.makeValidFilename(prefix) + "-" : "");
    if (sanitizedPrefix.length()>101) sanitizedPrefix = sanitizedPrefix.substring(0, 100)+"--";
    String extWithPrecedingSeparator = (Strings.isNonEmpty(ext) ? ext.startsWith(".") || ext.length()>4 ? ext : "."+ext : "");
    if (extWithPrecedingSeparator.length()>13) sanitizedPrefix = sanitizedPrefix.substring(0, 12)+"--";
    try {
        File tempFile = File.createTempFile(sanitizedPrefix, extWithPrecedingSeparator, new File(tmp()));
        tempFile.deleteOnExit();
        return tempFile;
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }
}
 
Example 6
Source File: MavenArtifact.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public String getFilename() {
    return artifactId+"-"+
            (Strings.isNonEmpty(getCustomFileNameAfterArtifactMarker()) ? getCustomFileNameAfterArtifactMarker()+"-" : "")+
            version+
            (Strings.isNonEmpty(getClassifierFileNameMarker()) ? "-"+getClassifierFileNameMarker() : "")+
            (Strings.isNonEmpty(getExtension()) ? "."+getExtension() : "");
}
 
Example 7
Source File: AbstractSoftwareProcessSshDriver.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void prepare() {
    // Check if we should create a download resolver?
    String downloadUrl = getEntity().config().get(SoftwareProcess.DOWNLOAD_URL);
    if (Strings.isNonEmpty(downloadUrl)) {
        resolver = Entities.newDownloader(this);
        String formatString = getArchiveNameFormat();
        if (Strings.isNonEmpty(formatString)) {
            setExpandedInstallDir(Os.mergePaths(getInstallDir(), resolver.getUnpackedDirectoryName(String.format(formatString, getVersion()))));
        } else {
            setExpandedInstallDir(getInstallDir());
        }
    }
}
 
Example 8
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 9
Source File: TestFrameworkAssertions.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private static boolean conditionHolds(String condition, Object actual, Object expected) {
    switch (condition) {
    case IS_EQUAL_TO:
    case EQUAL_TO:
    case EQUALS:
        return null != actual && actual.equals(expected);
    case NOT_EQUAL:
        return !Objects.equals(actual, expected);
    case IS_NULL:
        return isTrue(expected) == (null == actual);
    case NOT_NULL:
        return isTrue(expected) == (null != actual);
    case CONTAINS:
        return null != actual && actual.toString().contains(expected.toString());
    case IS_EMPTY:
        return isTrue(expected) == (null == actual || Strings.isEmpty(actual.toString()));
    case NOT_EMPTY:
        return isTrue(expected) == ((null != actual && Strings.isNonEmpty(actual.toString())));
    case MATCHES:
        Pattern matchesPattern = Pattern.compile(expected.toString());
        return null != actual && matchesPattern.matcher(actual.toString()).matches();
    case CONTAINS_MATCH:
        Pattern containsMatchPattern = Pattern.compile(expected.toString());
        return null != actual && containsMatchPattern.matcher(actual.toString()).find();
    case HAS_TRUTH_VALUE:
        return isTrue(expected) == isTrue(actual);
    case GREATER_THAN:
        return canCompare(actual, expected) && compare(actual, expected) > 0;
    case LESS_THAN:
        return canCompare(actual, expected) && compare(actual, expected) < 0;
    default:
        return false;
    }
}
 
Example 10
Source File: ReflectionScanner.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** as {@link #ReflectionScanner(Iterable, String, Predicate, ClassLoader...)} using the prefix as the base for the filter */
public ReflectionScanner(
        final Iterable<URL> urlsToScan, 
        final String optionalPrefix,
        final ClassLoader ...classLoaders) {
    this(urlsToScan, optionalPrefix, 
        Strings.isNonEmpty(optionalPrefix) ? new FilterBuilder.Include(FilterBuilder.prefix(optionalPrefix)) : null,
        classLoaders);
}
 
Example 11
Source File: BasicTask.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    // give display name plus id, or job and tags plus id; some jobs have been extended to include nice tostrings 
    return "Task["+
        (Strings.isNonEmpty(displayName) ? 
            displayName : 
            (job + (tags!=null && !tags.isEmpty() ? ";"+tags : "")) ) +
        "]@"+getId();
}
 
Example 12
Source File: EntityManagementUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** Modifies the child so it includes the inessential setup of its parent,
 * for use when unwrapping specific children, but a name or other item may have been set on the parent.
 * See {@link #WRAPPER_APP_MARKER}. */
private static void mergeWrapperParentSpecToChildEntity(EntitySpec<? extends Application> wrapperParent, EntitySpec<?> wrappedChild) {
    if (Strings.isNonEmpty(wrapperParent.getDisplayName())) {
        wrappedChild.displayName(wrapperParent.getDisplayName());
    }
    
    wrappedChild.locationSpecs(wrapperParent.getLocationSpecs());
    wrappedChild.locations(wrapperParent.getLocations());
    
    if (!wrapperParent.getParameters().isEmpty()) {
        wrappedChild.parametersAdd(wrapperParent.getParameters());
    }

    wrappedChild.catalogItemIdAndSearchPath(wrapperParent.getCatalogItemId(), wrapperParent.getCatalogItemIdSearchPath());

    // NB: this clobber's child config wherever they conflict; might prefer to deeply merge maps etc
    // (or maybe even prevent the merge in these cases; 
    // not sure there is a compelling reason to have config on a pure-wrapper parent)
    Map<ConfigKey<?>, Object> configWithoutWrapperMarker =
        Maps.filterKeys(wrapperParent.getConfig(),
            Predicates.not(Predicates.<ConfigKey<?>>equalTo(EntityManagementUtils.WRAPPER_APP_MARKER)));
    wrappedChild.configure(configWithoutWrapperMarker);
    wrappedChild.configure(wrapperParent.getFlags());
    
    // copying tags to all entities may be something the caller wants to control,
    // e.g. if we're adding multiple, the caller might not want to copy the parent
    // (the BrooklynTags.YAML_SPEC tag will include the parents source including siblings),
    // but OTOH they might because otherwise the parent's tags might get lost.
    // also if we are unwrapping multiple registry references we will get the YAML_SPEC for each;
    // putting the parent's tags first however causes the preferred (outer) one to be retrieved first.
    wrappedChild.tagsReplace(MutableList.copyOf(wrapperParent.getTags()).appendAll(wrappedChild.getTags()));
}
 
Example 13
Source File: BrooklynPropertiesFactoryHelper.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public BrooklynProperties.Factory.Builder createPropertiesBuilder() {
    if (brooklynProperties == null) {
        BrooklynProperties.Factory.Builder builder = BrooklynProperties.Factory.builderDefault();

        if (Strings.isNonEmpty(globalBrooklynPropertiesFile)) {
            File globalProperties = new File(Os.tidyPath(globalBrooklynPropertiesFile));
            if (globalProperties.exists()) {
                globalProperties = resolveSymbolicLink(globalProperties);
                checkFileReadable(globalProperties);
                // brooklyn.properties stores passwords (web-console and cloud credentials),
                // so ensure it has sensible permissions
                checkFilePermissionsX00(globalProperties);
                LOG.debug("Using global properties file " + globalProperties);
            } else {
                LOG.debug("Global properties file " + globalProperties + " does not exist, will ignore");
            }
            builder.globalPropertiesFile(globalProperties.getAbsolutePath());
        } else {
            LOG.debug("Global properties file disabled");
            builder.globalPropertiesFile(null);
        }
        
        if (Strings.isNonEmpty(localBrooklynPropertiesFile)) {
            File localProperties = new File(Os.tidyPath(localBrooklynPropertiesFile));
            localProperties = resolveSymbolicLink(localProperties);
            checkFileReadable(localProperties);
            checkFilePermissionsX00(localProperties);
            builder.localPropertiesFile(localProperties.getAbsolutePath());
        }

        if (propertiesSupplier != null) {
            builder.propertiesSupplier(propertiesSupplier);
        }
        return builder;
    } else {
        if (globalBrooklynPropertiesFile != null)
            LOG.warn("Ignoring globalBrooklynPropertiesFile "+globalBrooklynPropertiesFile+" because explicit brooklynProperties supplied");
        if (localBrooklynPropertiesFile != null)
            LOG.warn("Ignoring localBrooklynPropertiesFile "+localBrooklynPropertiesFile+" because explicit brooklynProperties supplied");
        return Builder.fromProperties(brooklynProperties);
    }
}
 
Example 14
Source File: BrooklynWebServer.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private SslContextFactory createContextFactory() throws KeyStoreException {
    SslContextFactory sslContextFactory = new SslContextFactory();

    // allow webconsole keystore & related properties to be set in brooklyn.properties
    String ksUrl = getKeystoreUrl();
    String ksPassword = getConfig(keystorePassword, BrooklynWebConfig.KEYSTORE_PASSWORD);
    String ksCertAlias = getConfig(keystoreCertAlias, BrooklynWebConfig.KEYSTORE_CERTIFICATE_ALIAS);
    String trProtos = getConfig(transportProtocols, BrooklynWebConfig.TRANSPORT_PROTOCOLS);
    String trCiphers = getConfig(transportCiphers, BrooklynWebConfig.TRANSPORT_CIPHERS);
    
    if (ksUrl!=null) {
        sslContextFactory.setKeyStorePath(getLocalKeyStorePath(ksUrl));
        if (Strings.isEmpty(ksPassword))
            throw new IllegalArgumentException("Keystore password is required and non-empty if keystore is specified.");
        sslContextFactory.setKeyStorePassword(ksPassword);
        if (Strings.isNonEmpty(ksCertAlias))
            sslContextFactory.setCertAlias(ksCertAlias);
    } else {
        log.info("No keystore specified but https enabled; creating a default keystore");
        
        if (Strings.isEmpty(ksCertAlias))
            ksCertAlias = "web-console";
        
        // if password is blank the process will block and read from stdin !
        if (Strings.isEmpty(ksPassword)) {
            ksPassword = Identifiers.makeRandomId(8);
            log.debug("created random password "+ksPassword+" for ad hoc internal keystore");
        }
        
        KeyStore ks = SecureKeys.newKeyStore();
        KeyPair key = SecureKeys.newKeyPair();
        X509Certificate cert = new FluentKeySigner("brooklyn").newCertificateFor("web-console", key);
        ks.setKeyEntry(ksCertAlias, key.getPrivate(), ksPassword.toCharArray(),
            new Certificate[] { cert });
        
        sslContextFactory.setKeyStore(ks);
        sslContextFactory.setKeyStorePassword(ksPassword);
        sslContextFactory.setCertAlias(ksCertAlias);
    }
    if (!Strings.isEmpty(truststorePath)) {
        sslContextFactory.setTrustStorePath(checkFileExists(truststorePath, "truststore"));
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }

    if (Strings.isNonBlank(trProtos)) {
        sslContextFactory.setIncludeProtocols(parseArray(trProtos));
    }
    if (Strings.isNonBlank(trCiphers)) {
        sslContextFactory.setIncludeCipherSuites(parseArray(trCiphers));
    }
    return sslContextFactory;
}
 
Example 15
Source File: Main.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected BrooklynLauncher createLauncher() {
    BrooklynLauncher launcher;
    launcher = BrooklynLauncher.newInstance();
    launcher.localBrooklynPropertiesFile(localBrooklynProperties)
            .ignorePersistenceErrors(!startupFailOnPersistenceErrors)
            .ignoreCatalogErrors(!startupFailOnCatalogErrors)
            .ignoreWebErrors(startupContinueOnWebErrors)
            .ignoreAppErrors(!startupFailOnManagedAppsErrors)
            .locations(Strings.isBlank(locations) ? ImmutableList.<String>of() : JavaStringEscapes.unwrapJsonishListStringIfPossible(locations));
    
    launcher.restServer(!noConsole);
    if (useHttps) {
        // true sets it; false (not set) leaves it blank and falls back to config key
        // (no way currently to override config key, but that could be added)
        launcher.restServerHttps(useHttps);
    }
    launcher.restServerPort(port);
    
    if (noGlobalBrooklynProperties) {
        log.debug("Configuring to disable global brooklyn.properties");
        launcher.globalBrooklynPropertiesFile(null);
    }
    if (noConsoleSecurity) {
        log.info("Configuring to disable console security");
        launcher.installSecurityFilter(false);
    }
    if (startBrooklynNode) {
        log.info("Configuring BrooklynNode entity startup");
        launcher.startBrooklynNode(true);
    }
    if (Strings.isNonEmpty(bindAddress)) {
        log.debug("Configuring bind address as "+bindAddress);
        launcher.bindAddress(Networking.getInetAddressWithFixedName(bindAddress));
    }
    if (Strings.isNonEmpty(publicAddress)) {
        log.debug("Configuring public address as "+publicAddress);
        launcher.publicAddress(Networking.getInetAddressWithFixedName(publicAddress));
    }
    if (explicitManagementContext!=null) {
        log.debug("Configuring explicit management context "+explicitManagementContext);
        launcher.managementContext(explicitManagementContext);
    }
    return launcher;
}