Java Code Examples for org.apache.brooklyn.util.text.Strings#removeFromStart()
The following examples show how to use
org.apache.brooklyn.util.text.Strings#removeFromStart() .
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: TemplateProcessor.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Override public TemplateModel get(String key) { if (map==null) return null; try { if (map.containsKey(key)) return wrapAsTemplateModel( map.get(key) ); Map<String,Object> result = MutableMap.of(); for (Map.Entry<?,?> entry: map.entrySet()) { String k = Strings.toString(entry.getKey()); if (k.startsWith(key+".")) { String k2 = Strings.removeFromStart(k, key+"."); result.put(k2, entry.getValue()); } } if (!result.isEmpty()) return wrapAsTemplateModel( result ); } catch (Exception e) { Exceptions.propagateIfFatal(e); throw new IllegalStateException("Error accessing config '"+key+"'"+": "+e, e); } return null; }
Example 2
Source File: SecurityGroupTool.java From brooklyn-server with Apache License 2.0 | 5 votes |
protected SecurityGroup findSecurityGroupWithName(SecurityGroupExtension sgExt, String name) { Set<SecurityGroup> groups = sgExt.listSecurityGroups(); // jclouds appends this sometimes so for portability let's add this String nameAlt = name.startsWith("jclouds#") ? Strings.removeFromStart(name, "jclouds#") : "jclouds#"+name; for (SecurityGroup g: groups) { if (name.equals(g.getName())) return g; if (nameAlt.equals(g.getName())) return g; } return null; }
Example 3
Source File: DslToStringHelpers.java From brooklyn-server with Apache License 2.0 | 5 votes |
/** convenience for internal arguments, removing any prefix, and applying wrap/escapes and other conversions */ public static String internal(Object x) { if (x==null) return "null"; if (x instanceof String) return JavaStringEscapes.wrapJavaString((String)x); if (x instanceof BrooklynObject) return fn("entity", MutableList.of( ((BrooklynObject)x).getId() )); return Strings.removeFromStart(x.toString(), BrooklynDslCommon.PREFIX); }
Example 4
Source File: BrooklynDslInterpreter.java From brooklyn-server with Apache License 2.0 | 5 votes |
public Object evaluateOn(Object o, FunctionWithArgs f, boolean deepEvaluation) { if (f.getArgs()==null) throw new IllegalStateException("Invalid function-only expression '"+f.getFunction()+"'"); String fn = f.getFunction(); fn = Strings.removeFromStart(fn, BrooklynDslCommon.PREFIX); if (fn.startsWith("function.")) { // If the function name starts with 'function.', then we look for the function in BrooklynDslCommon.Functions // As all functions in BrooklynDslCommon.Functions are static, we don't need to worry whether a class // or an instance was passed into this method o = BrooklynDslCommon.Functions.class; fn = Strings.removeFromStart(fn, "function."); } List<Object> args = new ArrayList<>(); for (Object arg: f.getArgs()) { args.add( deepEvaluation ? evaluate(arg, true) : arg ); } try { // TODO Could move argument resolve in DslDeferredFunctionCall freeing each Deffered implementation // having to handle it separately. The shortcoming is that will lose the eager evaluation we have here. if (o instanceof BrooklynDslDeferredSupplier && !(o instanceof DslFunctionSource)) { return new DslDeferredFunctionCall(o, fn, args); } else { // Would prefer to keep the invocation logic encapsulated in DslDeferredFunctionCall, but // for backwards compatibility will evaluate as much as possible eagerly (though it shouldn't matter in theory). return DslDeferredFunctionCall.invokeOn(o, fn, args).get(); } } catch (Exception e) { Exceptions.propagateIfFatal(e); throw Exceptions.propagate(new InvocationTargetException(e, "Error invoking '"+fn+"' on '"+o+"' with arguments "+args+"")); } }
Example 5
Source File: BrooklynRestResourceUtils.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Deprecated public static String fixLocation(String locationId) { if (locationId.startsWith("/locations/") || locationId.startsWith("/v1/locations/")) { log.warn("REST API using legacy URI syntax for location: "+locationId); locationId = Strings.removeFromStart(locationId, "/v1/locations/"); locationId = Strings.removeFromStart(locationId, "/locations/"); } return locationId; }
Example 6
Source File: HttpExecutorFactoryImpl.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Override public HttpExecutor getHttpExecutor(Map<?, ?> props) { HttpExecutor httpExecutor; String httpExecutorClass = (String) props.get(HTTP_EXECUTOR_CLASS_CONFIG); if (httpExecutorClass != null) { Map<String,Object> httpExecutorProps = MutableMap.of(); Map<?, ?> executorProps = Maps.filterKeys(props, StringPredicates.isStringStartingWith(HTTP_EXECUTOR_CLASS_CONFIG_PREFIX)); if (executorProps.size() > 0) { for (Entry<?, ?> entry: executorProps.entrySet()) { String keyName = Strings.removeFromStart((String)entry.getKey(), HTTP_EXECUTOR_CLASS_CONFIG_PREFIX); httpExecutorProps.put(keyName, entry.getValue()); } } try { httpExecutor = (HttpExecutor) new ClassLoaderUtils(getClass()).loadClass(httpExecutorClass).getConstructor(Map.class).newInstance(httpExecutorProps); } catch (Exception e) { throw Exceptions.propagate(e); } } else { LOG.info(HTTP_EXECUTOR_CLASS_CONFIG + " parameter not provided. Using the default implementation " + HttpExecutorImpl.class.getName()); httpExecutor = HttpExecutorImpl.newInstance(); } return httpExecutor; }
Example 7
Source File: BasicBrooklynCatalog.java From brooklyn-server with Apache License 2.0 | 5 votes |
/** See comments on {@link #collectCatalogItemsFromItemMetadataBlock(String, ManagedBundle, Map, List, boolean, Map, int, boolean)}; * this is a shell around that that parses the `brooklyn.catalog` header on the BOM YAML file */ private void collectCatalogItemsFromCatalogBomRoot(String contextForError, String yaml, ManagedBundle containingBundle, List<CatalogItemDtoAbstract<?, ?>> resultLegacyFormat, Map<RegisteredType, RegisteredType> resultNewFormat, boolean requireValidation, Map<?, ?> parentMeta, int depth, boolean force) { Map<?,?> itemDef; try { itemDef = Yamls.getAs(Yamls.parseAll(yaml), Map.class); } catch (Exception e) { throw Exceptions.propagateAnnotated("Error parsing YAML in "+contextForError, e); } Map<?,?> catalogMetadata = getFirstAsMap(itemDef, "brooklyn.catalog").orNull(); if (catalogMetadata==null) log.warn("No `brooklyn.catalog` supplied in catalog request; using legacy mode for "+itemDef); catalogMetadata = MutableMap.copyOf(catalogMetadata); collectCatalogItemsFromItemMetadataBlock(Yamls.getTextOfYamlAtPath(yaml, "brooklyn.catalog").getMatchedYamlTextOrWarn(), containingBundle, catalogMetadata, resultLegacyFormat, resultNewFormat, requireValidation, parentMeta, 0, force); itemDef.remove("brooklyn.catalog"); catalogMetadata.remove("item"); catalogMetadata.remove("items"); if (!itemDef.isEmpty()) { // AH - i forgot we even supported this. probably no point anymore, // now that catalog defs can reference an item yaml and things can be bundled together? log.warn("Deprecated read of catalog item from sibling keys of `brooklyn.catalog` section, " + "instead of the more common appraoch of putting inside an `item` within it. " + "Rewrite to use nested/reference syntax instead or contact the community for assistance or feedback."); Map<String,?> rootItem = MutableMap.of("item", itemDef); String rootItemYaml = yaml; YamlExtract yamlExtract = Yamls.getTextOfYamlAtPath(rootItemYaml, "brooklyn.catalog"); String match = yamlExtract.withOriginalIndentation(true).withKeyIncluded(true).getMatchedYamlTextOrWarn(); if (match!=null) { if (rootItemYaml.startsWith(match)) rootItemYaml = Strings.removeFromStart(rootItemYaml, match); else rootItemYaml = Strings.replaceAllNonRegex(rootItemYaml, "\n"+match, ""); } collectCatalogItemsFromItemMetadataBlock("item:\n"+makeAsIndentedObject(rootItemYaml), containingBundle, rootItem, resultLegacyFormat, resultNewFormat, requireValidation, catalogMetadata, 1, force); } }
Example 8
Source File: PerUserEntitlementManager.java From brooklyn-server with Apache License 2.0 | 5 votes |
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+")"); }
Example 9
Source File: NamedLocationResolver.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Override public LocationSpec<? extends Location> newLocationSpecFromString(String spec, Map<?, ?> locationFlags, LocationRegistry registry) { String name = spec; ConfigBag lfBag = ConfigBag.newInstance(locationFlags).putIfAbsent(LocationInternal.ORIGINAL_SPEC, name); name = Strings.removeFromStart(spec, getPrefix()+":"); if (name.toLowerCase().startsWith(NAMED+":")) { // since 0.7.0 log.warn("Deprecated use of 'named:' prefix with wrong case ("+spec+"); support may be removed in future versions"); name = spec.substring( (NAMED+":").length() ); } LocationDefinition ld = registry.getDefinedLocationByName(name); if (ld==null) throw new NoSuchElementException("No named location defined matching '"+name+"'"); return registry.getLocationSpec(ld, lfBag.getAllConfig()).get(); }
Example 10
Source File: WinRmMachineLocation.java From brooklyn-server with Apache License 2.0 | 4 votes |
protected WinRmTool newWinRmTool(Map<?,?> props) { // TODO See comments/TODOs in SshMachineLocation.connectSsh() try { ConfigBag args = new ConfigBag(); for (Map.Entry<ConfigKey<?>, ?> entry: config().getBag().getAllConfigAsConfigKeyMap().entrySet()) { boolean include = false; String keyName = entry.getKey().getName(); if (keyName.startsWith(WinRmTool.BROOKLYN_CONFIG_KEY_PREFIX)) { keyName = Strings.removeFromStart(keyName, WinRmTool.BROOKLYN_CONFIG_KEY_PREFIX); include = true; } if (keyName.startsWith(WINRM_TOOL_CLASS_PROPERTIES_PREFIX)) { keyName = Strings.removeFromStart(keyName, WINRM_TOOL_CLASS_PROPERTIES_PREFIX); include = true; } if (ALL_WINRM_CONFIG_KEY_NAMES.contains(keyName)) { // key should be included, and does not need to be changed // TODO make this config-setting mechanism more universal // currently e.g. it will not admit a tool-specific property. // thinking either we know about the tool here, // or we don't allow unadorned keys to be set // (require use of BROOKLYN_CONFIG_KEY_PREFIX) include = true; } if (include) { args.putStringKey(keyName, config().get(entry.getKey())); } } args.putAll(props); args.configure(SshTool.PROP_HOST, getAddress().getHostAddress()); args.configure(WinRmTool.USE_NTLM, getConfig(WinRmMachineLocation.USE_NTLM)); args.configure(WinRmTool.PROP_PORT, getPort()); if (LOG.isTraceEnabled()) LOG.trace("creating WinRM session for "+Sanitizer.sanitize(args)); // look up tool class String toolClass = args.get(WINRM_TOOL_CLASS); if (toolClass == null) toolClass = Winrm4jTool.class.getName(); WinRmTool tool = (WinRmTool) new ClassLoaderUtils(this, getManagementContext()).loadClass(toolClass).getConstructor(Map.class).newInstance(args.getAllConfig()); if (tool instanceof ManagementContextInjectable) { ((ManagementContextInjectable)tool).setManagementContext(getManagementContext()); } if (LOG.isTraceEnabled()) LOG.trace("using ssh-tool {} (of type {}); props ", tool, toolClass); return tool; } catch (Exception e) { throw Exceptions.propagate(e); } }
Example 11
Source File: SshMachineLocation.java From brooklyn-server with Apache License 2.0 | 4 votes |
protected SshTool connectSsh(Map<?,?> props) { try { if (!groovyTruth(user)) { String newUser = getUser(); if (LOG.isTraceEnabled()) LOG.trace("For "+this+", setting user in connectSsh: oldUser="+user+"; newUser="+newUser); user = newUser; } ConfigBag args = new ConfigBag() .configure(SshTool.PROP_USER, user) // default value of host, overridden if SSH_HOST is supplied .configure(SshTool.PROP_HOST, address.getHostName()); for (Map.Entry<ConfigKey<?>, ?> entry: config().getBag().getAllConfigAsConfigKeyMap().entrySet()) { boolean include = false; String keyName = entry.getKey().getName(); if (keyName.startsWith(SshTool.BROOKLYN_CONFIG_KEY_PREFIX)) { keyName = Strings.removeFromStart(keyName, SshTool.BROOKLYN_CONFIG_KEY_PREFIX); include = true; } if (keyName.startsWith(SSH_TOOL_CLASS_PROPERTIES_PREFIX)) { keyName = Strings.removeFromStart(keyName, SSH_TOOL_CLASS_PROPERTIES_PREFIX); include = true; } if (ALL_SSH_CONFIG_KEY_NAMES.contains(keyName)) { // key should be included, and does not need to be changed // TODO make this config-setting mechanism more universal // currently e.g. it will not admit a tool-specific property. // thinking either we know about the tool here, // or we don't allow unadorned keys to be set // (require use of BROOKLYN_CONFIG_KEY_PREFIX) include = true; } if (include) { args.putStringKey(keyName, config().get(entry.getKey())); } } // Explicit props trump all. args.putAll(props); if (LOG.isTraceEnabled()) LOG.trace("creating ssh session for "+Sanitizer.sanitize(args)); if (!user.equals(args.get(SshTool.PROP_USER))) { LOG.warn("User mismatch configuring ssh for "+this+": preferring user "+args.get(SshTool.PROP_USER)+" over "+user); user = args.get(SshTool.PROP_USER); } // look up tool class String sshToolClass = args.get(SSH_TOOL_CLASS); String legacySshToolClass = args.get(SshTool.PROP_TOOL_CLASS); if (Strings.isNonBlank(legacySshToolClass)) { String msg; if (Strings.isNonBlank(sshToolClass)) { msg = "Ignoring deprecated config "+SshTool.PROP_TOOL_CLASS.getName()+"="+legacySshToolClass +", preferring "+SSH_TOOL_CLASS.getName()+"="+sshToolClass+" for "+SshMachineLocation.this; } else { sshToolClass = legacySshToolClass; msg = "Using deprecated config "+SshTool.PROP_TOOL_CLASS.getName()+"="+legacySshToolClass +", preferring "+SSH_TOOL_CLASS.getName()+"="+sshToolClass+" for "+SshMachineLocation.this; } if (!loggedLegcySshToolClassConfig) { LOG.warn(msg); loggedLegcySshToolClassConfig = true; } } if (sshToolClass==null) sshToolClass = SshjTool.class.getName(); SshTool ssh = (SshTool) new ClassLoaderUtils(this, getManagementContext()).loadClass(sshToolClass).getConstructor(Map.class).newInstance(args.getAllConfig()); if (LOG.isTraceEnabled()) LOG.trace("using ssh-tool {} (of type {}); props ", ssh, sshToolClass); Tasks.setBlockingDetails("Opening ssh connection"); try { ssh.connect(); } finally { Tasks.setBlockingDetails(null); } previouslyConnected = true; return ssh; } catch (Exception e) { if (previouslyConnected) throw Throwables.propagate(e); // subsequence connection (above) most likely network failure, our remarks below won't help // on first connection include additional information if we can't connect, to help with debugging String rootCause = Throwables.getRootCause(e).getMessage(); throw new IllegalStateException("Cannot establish ssh connection to "+user+" @ "+this+ (rootCause!=null && !rootCause.isEmpty() ? " ("+rootCause+")" : "")+". \n"+ "Ensure that passwordless and passphraseless ssh access is enabled using standard keys from ~/.ssh or " + "as configured in brooklyn.properties. " + "Check that the target host is accessible, " + "that credentials are correct (location and permissions if using a key), " + "that the SFTP subsystem is available on the remote side, " + "and that there is sufficient random noise in /dev/random on both ends. " + "To debug less common causes, see the original error in the trace or log, and/or enable 'net.schmizz' (sshj) logging." , e); } }
Example 12
Source File: CatalogLocationResolver.java From brooklyn-server with Apache License 2.0 | 4 votes |
@Beta /** for transitioning away from LocationDefinition */ public static String unwrapLegacyWrappedReference(String id) { return Strings.removeFromStart(id, NAME+":"); }