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

The following examples show how to use org.apache.brooklyn.util.text.Strings#makeValidFilename() . 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: Os.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** creates a temp dir which will be deleted on exit */
public static File newTempDir(String prefix) {
    String sanitizedPrefix = (prefix==null ? "" : Strings.makeValidFilename(prefix) + "-");
    String tmpParent = tmp();
    
    //With lots of stale temp dirs it is possible to have 
    //name collisions so we need to retry until a unique 
    //name is found
    for (int i = 0; i < TEMP_DIR_ATTEMPTS; i++) {
        String baseName = sanitizedPrefix + Identifiers.makeRandomId(4);
        File tempDir = new File(tmpParent, baseName);
        if (!tempDir.exists()) {
            if (tempDir.mkdir()) {
                Os.deleteOnExitRecursively(tempDir);
                return tempDir;
            } else {
                log.warn("Attempt to create temp dir failed " + tempDir + ". Either an IO error (disk full, no rights) or someone else created the folder after the !exists() check.");
            }
        } else {
            log.debug("Attempt to create temp dir failed, already exists " + tempDir + ". With ID of length 4 it is not unusual (15% chance) to have duplicate names at the 2000 samples mark.");
        }
    }
    throw new IllegalStateException("cannot create temporary folders in parent " + tmpParent + " after " + TEMP_DIR_ATTEMPTS + " attempts.");
}
 
Example 2
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 3
Source File: ChefLifecycleEffectorTasks.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
protected String getNodeName() {
    // (node name is needed so we can node delete it)
    
    // TODO would be better if CHEF_NODE_NAME were a freemarker template, could access entity.id, or hostname, etc,
    // in addition to supporting hard-coded node names (which is all we support so far).
    
    String nodeName = entity().getConfig(ChefConfig.CHEF_NODE_NAME);
    if (Strings.isNonBlank(nodeName)) return Strings.makeValidFilename(nodeName);
    // node name is taken from ID of this entity, if not specified
    return entity().getId();
}
 
Example 4
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 5
Source File: CouchbaseClusterImpl.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
/** finds the cluster name specified for a node or a cluster, 
 * using {@link CouchbaseCluster#CLUSTER_NAME} or falling back to the cluster (or node) ID. */
public static String getClusterName(Entity node) {
    String name = node.getConfig(CLUSTER_NAME);
    if (!Strings.isBlank(name)) return Strings.makeValidFilename(name);
    return getClusterOrNode(node).getId();
}
 
Example 6
Source File: JavaClassNames.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/** as {@link #simpleClassName(Object)} but making the result clean for use on filesystems and as java identifiers */
public static String cleanSimpleClassName(Object x) {
    return Strings.makeValidFilename(simpleClassName(x));
}
 
Example 7
Source File: JavaClassNames.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/** as {@link #simpleClassName(Object)} but making the result clean for use on filesystems and as java identifiers */
public static String cleanSimpleClassName(Class<?> x) {
    return Strings.makeValidFilename(simpleClassName(x));
}
 
Example 8
Source File: StringsTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = { NullPointerException.class })
public void testMakeValidFilenameNull() {
    Strings.makeValidFilename(null);
}
 
Example 9
Source File: StringsTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = { IllegalArgumentException.class })
public void testMakeValidFilenameEmpty() {
    Strings.makeValidFilename("");
}
 
Example 10
Source File: StringsTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions = { IllegalArgumentException.class })
public void testMakeValidFilenameBlank() {
    Strings.makeValidFilename("    \t    ");
}
 
Example 11
Source File: BrooklynTypeSnapshot.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private String toSimpleName(String name) {
    String simpleName = name.substring(name.lastIndexOf(".")+1);
    if (Strings.isBlank(simpleName)) simpleName = name.trim();
    return Strings.makeValidFilename(simpleName);
}
 
Example 12
Source File: BrooklynMementoPersisterToObjectStore.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public BrooklynMementoRawData loadMementoRawData(final RebindExceptionHandler exceptionHandler) {
    BrooklynMementoRawData subPathData = listMementoSubPathsAsData(exceptionHandler);
    
    final BrooklynMementoRawData.Builder builder = BrooklynMementoRawData.builder();
    
    Visitor loaderVisitor = new Visitor() {
        @Override
        public void visit(BrooklynObjectType type, String id, String contentsSubpath) throws Exception {
            if (type == BrooklynObjectType.MANAGED_BUNDLE && id.endsWith(".jar")) {
                // don't visit jar files directly; someone else will read them
                return;
            }
            
            String contents = null;
            try {
                contents = read(contentsSubpath);
            } catch (Exception e) {
                Exceptions.propagateIfFatal(e);
                exceptionHandler.onLoadMementoFailed(type, "memento "+id+" read error", e);
            }
            
            String xmlId = (String) XmlUtil.xpathHandlingIllegalChars(contents, "/"+type.toCamelCase()+"/id");
            String safeXmlId = Strings.makeValidFilename(xmlId);
            if (!Objects.equal(id, safeXmlId))
                LOG.warn("ID mismatch on "+type.toCamelCase()+", "+id+" from path, "+safeXmlId+" from xml");
            
            if (type == BrooklynObjectType.MANAGED_BUNDLE) {
                // TODO could R/W to cache space directly, rather than memory copy then extra file copy
                byte[] jarData = readBytes(contentsSubpath+".jar");
                if (jarData==null) {
                    throw new IllegalStateException("No bundle data for "+contentsSubpath);
                }
                builder.bundleJar(id, ByteSource.wrap(jarData));
            }
            builder.put(type, xmlId, contents);
        }
    };

    Stopwatch stopwatch = Stopwatch.createStarted();

    builder.planeId(Strings.emptyToNull(read(PLANE_ID_FILE_NAME)));
    visitMemento("loading raw", subPathData, loaderVisitor, exceptionHandler);
    
    BrooklynMementoRawData result = builder.build();

    if (LOG.isDebugEnabled()) {
        LOG.debug("Loaded rebind raw data; took {}; {} entities, {} locations, {} policies, {} enrichers, {} feeds, {} catalog items, {} bundles, from {}", new Object[]{
                 Time.makeTimeStringRounded(stopwatch.elapsed(TimeUnit.MILLISECONDS)), result.getEntities().size(), 
                 result.getLocations().size(), result.getPolicies().size(), result.getEnrichers().size(),
                 result.getFeeds().size(), result.getCatalogItems().size(), result.getBundles().size(),
                 objectStore.getSummaryName() });
    }

    return result;
}
 
Example 13
Source File: BrooklynMementoPersisterToObjectStore.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private String getPath(String subPath, String id) {
    return subPath+"/"+Strings.makeValidFilename(id);
}