/** NB: might be useful for stack trace, e.g. {@link ExecutionException} */ private static boolean isBoringForMessage(Throwable t) { for (Class<? extends Throwable> type: ALWAYS_BORING_MESSAGE_THROWABLE_SUPERTYPES) if (type.isInstance(t)) return true; if (Strings.isBlank(t.getMessage())) { for (Class<? extends Throwable> type: BORING_IF_NO_MESSAGE_THROWABLE_SUPERTYPES) if (type.isInstance(t)) return true; } return false; }
@Override public String toString() { return getClass().getSimpleName()+"["+ (Strings.isNonBlank(publicKeyData) ? publicKeyData : "no-public-key")+";"+ (Strings.isNonBlank(privateKeyData) ? "private-key-present" : "no-private-key")+","+ (password!=null ? "password(len="+password.length()+")" : "no-password")+"]"; } }
/** * Removes prefix from the beginning of string. Returns string if it does not begin with prefix. */ public static String removeFromStart(String string, String prefix) { if (isEmpty(string)) { return string; } else if (!isEmpty(prefix) && string.startsWith(prefix)) { return string.substring(prefix.length()); } else { return string; } }
private String toSimpleName(String name) { String simpleName = name.substring(name.lastIndexOf(".")+1); if (Strings.isBlank(simpleName)) simpleName = name.trim(); return Strings.makeValidFilename(simpleName); }
@Override public boolean isAuthenticated(HttpSession session) { if (session == null) return false; Object value = session.getAttribute(getAuthenticationKey()); return Strings.isNonBlank(Strings.toString(value)); }
/** puts a prefix in front of the message, with the given separator if there is already a message; * if there is no message, it simply sets the prefix as the message. * if no prefix or blank, does nothing. */ public Builder prefixMessage(String prefix, String separatorIfMessageNotBlank) { if (Strings.isNonBlank(prefix)) { if (Strings.isBlank(message)) message(prefix); else message(prefix+separatorIfMessageNotBlank+message); } return this; }
public void isBlankOrEmpty() { assertTrue(Strings.isEmpty(null)); assertTrue(Strings.isEmpty("")); assertFalse(Strings.isEmpty(" \t ")); assertFalse(Strings.isEmpty("abc")); assertFalse(Strings.isEmpty(" abc ")); assertFalse(Strings.isNonEmpty(null)); assertFalse(Strings.isNonEmpty("")); assertTrue(Strings.isNonEmpty(" \t ")); assertTrue(Strings.isNonEmpty("abc")); assertTrue(Strings.isNonEmpty(" abc ")); assertTrue(Strings.isBlank(null)); assertTrue(Strings.isBlank("")); assertTrue(Strings.isBlank(" \t ")); assertFalse(Strings.isBlank("abc")); assertFalse(Strings.isBlank(" abc ")); assertFalse(Strings.isNonBlank(null)); assertFalse(Strings.isNonBlank("")); assertFalse(Strings.isNonBlank(" \t ")); assertTrue(Strings.isNonBlank("abc")); assertTrue(Strings.isNonBlank(" abc ")); }
/** * @return null if var is null or empty string, otherwise return var */ public static String emptyToNull(String var) { if (isNonEmpty(var)) { return var; } else { return null; } }
@Override public String toString() { return String.format("labelEqualTo(%s)",Strings.toString(label)); } }
private String getStorageOpts() { String driver = getEntity().config().get(DockerHost.DOCKER_STORAGE_DRIVER); if (Strings.isBlank(driver)) { return null; } else { return "-s " + Strings.toLowerCase(driver); } }
/** As {@link #chain(Collection)}, but explicitly using ( ) grouping characters * to ensure exits are caught. */ public static String chainSubshell(Collection<String> commands) { // the spaces are not required, but it might be possible that a (( expr )) is interpreted differently // (won't hurt to have the spaces in any case!) return "( " + Strings.join(commands, " && ") + " )"; }
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(); }
public PerUserEntitlementManager(BrooklynProperties properties) { this(load(properties, properties.getConfig(DEFAULT_MANAGER))); Set<ConfigKey<?>> users = properties.findKeysPresent(ConfigPredicates.nameStartsWith(PER_USER_ENTITLEMENTS_CONFIG_PREFIX+".")); for (ConfigKey<?> key: users) { if (key.getName().equals(DEFAULT_MANAGER.getName())) continue; String user = Strings.removeFromStart(key.getName(), PER_USER_ENTITLEMENTS_CONFIG_PREFIX+"."); addUser(user, load(properties, Strings.toString(properties.getConfig(key)))); } log.info(getClass().getSimpleName()+" created with "+perUserManagers.size()+" user"+Strings.s(perUserManagers)+" and " + "default "+defaultManager+" (users: "+perUserManagers+")"); }
private String getIdWithRandomDefault() { return idAsSymbolicNameWithoutVersion != null ? idAsSymbolicNameWithoutVersion : Strings.makeRandomId(10); } public Map<?,?> getItem() {
/** 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); } }
@Override public Double apply(SshPollValue input) { String q = Strings.getFirstWordAfter(input.getStdout(), "Queries per second avg:"); if (q==null) return null; return Double.parseDouble(q); }}) .setOnFailureOrException(null)
public static RangeSet<Integer> portRulesToRanges(Collection<String> portRules) { RangeSet<Integer> result = TreeRangeSet.create(); for (String portRule : portRules) { if (portRule.contains("-")) { String[] fromTo = portRule.split("-"); checkArgument(fromTo.length == 2, "Invalid port range '%s'", portRule); checkArgument(Strings.countOccurrences(portRule, '-') == 1, "Invalid port range '%s'", portRule); checkArgument(Strings.isNonEmpty(fromTo[0]), "Invalid port range '%s'", portRule); checkArgument(Strings.isNonEmpty(fromTo[1]), "Invalid port range '%s'", portRule); result.add(closedRange(fromTo[0], fromTo[1])); } else { result.add(closedRange(portRule, portRule)); } } return result; }
@Override public boolean apply(Application app) { VanillaWindowsProcess entity = Iterables.getOnlyElement(Entities.descendantsAndSelf(app, VanillaWindowsProcess.class)); String winRMAddress = entity.getAttribute(AdvertiseWinrmLoginPolicy.VM_USER_CREDENTIALS); String ipPort = Strings.getFirstWordAfter(winRMAddress, "@"); String user = Strings.getFirstWord(winRMAddress); String password = Strings.getFirstWordAfter(winRMAddress, ":"); WinRmTool winRmTool = WinRmTool.Builder.builder(ipPort, user, password).build(); WinRmToolResponse winRmResponse = winRmTool.executePs(ImmutableList.of("(Get-Item \"C:\\\\Program Files\\\\7-Zip\\\\7z.exe\").name")); LOG.info("winRmResponse: code="+winRmResponse.getStatusCode()+"; out="+winRmResponse.getStdOut()+"; err="+winRmResponse.getStdErr()); return "7z.exe\r\n".equals(winRmResponse.getStdOut()); } };
@Test(groups={"Integration", "Broken", "Manual"}) public void testRebindCheckingMemoryLeak() throws Exception { TestEntity c1 = origApp.addChild(EntitySpec.create(TestEntity.class)); c1.config().set(TestEntity.CONF_NAME, Strings.makeRandomId(1000000)); gcAndLog("before"); long used0 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); for (int i=0; i<200; i++) { doPartialRebindOfIds(c1.getId()); origManagementContext.getGarbageCollector().gcIteration(); gcAndLog("iteration "+i); if (i==5) used0 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); } gcAndLog("after"); long used1 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); Assert.assertTrue(used1 - used0 < 5000000, "Expected leak of less than 5M; leak was: from "+Strings.makeJavaSizeString(used0)+" to "+Strings.makeJavaSizeString(used1)); }
public static ConfigKey<?> newInstance(ConfigBag keyDefs) { String typeName = Strings.toString(keyDefs.getStringKey("type")); if (Strings.isNonBlank(typeName)) { // TODO dynamic typing - see TYPE key commented out above; also see AddSensor.getType for type lookup log.warn("Setting 'type' is not currently supported for dynamic config keys; ignoring in definition of "+keyDefs); } Class<Object> type = Object.class; String name = keyDefs.get(NAME); String description = keyDefs.get(DESCRIPTION); Object defaultValue = keyDefs.get(DEFAULT_VALUE); return newConfigKey(type, name, description, defaultValue); }