List of usage examples for org.apache.commons.lang StringUtils removeStart
public static String removeStart(String str, String remove)
Removes a substring only if it is at the begining of a source string, otherwise returns the source string.
From source file:org.onehippo.forge.solr.indexer.task.JcrUtils.java
/** * Get JCR property (nested property if path contains '/') * @param node JCR node/*from w w w .j ava2 s . co m*/ * @param propertyPath JCR property path * @return JCR property (nullable) */ public static Property getProperty(Node node, String propertyPath) { String propertyPathStripped = StringUtils.strip(propertyPath, PATH_SEPARATOR); try { if (StringUtils.contains(propertyPathStripped, PATH_SEPARATOR)) { String nodePath = StringUtils.split(propertyPathStripped, PATH_SEPARATOR)[0]; if (node.hasNode(nodePath)) { return getProperty(node.getNode(nodePath), StringUtils.removeStart(propertyPathStripped, nodePath)); } } else if (node.hasProperty(propertyPathStripped)) { return node.getProperty(propertyPathStripped); } } catch (RepositoryException e) { log.error("Failed to retrieve property " + propertyPath + " for node at " + getPath(node), e); } return null; }
From source file:org.openengsb.domain.presentation.operation.PrefixChangeOperation.java
/** * Performs the actual prefix change operation. Throws a TransformationOperationException if anything goes wrong * during the procedure.// www . j a v a 2 s . c o m */ public static String performPrefixChange(String source, String oldPrefix, String newPrefix) throws TransformationOperationException { try { source = StringUtils.removeStart(source, oldPrefix); return StringUtils.join(new Object[] { newPrefix, source }); } catch (Exception e) { throw new TransformationOperationException("Unable to perform prefix change operation", e); } }
From source file:org.openhab.binding.astro.internal.bus.BindingConfigParser.java
/** * Parses the bindingConfig of an item and returns a AstroBindingConfig. *///from w w w. j a v a 2s. c om public AstroBindingConfig parse(Item item, String bindingConfig) throws BindingConfigParseException { bindingConfig = StringUtils.trimToEmpty(bindingConfig); bindingConfig = StringUtils.removeStart(bindingConfig, "{"); bindingConfig = StringUtils.removeEnd(bindingConfig, "}"); String[] entries = bindingConfig.split("[,]"); AstroBindingConfigHelper helper = new AstroBindingConfigHelper(); for (String entry : entries) { String[] entryParts = StringUtils.trimToEmpty(entry).split("[=]"); if (entryParts.length != 2) { throw new BindingConfigParseException("A bindingConfig must have a key and a value"); } String key = StringUtils.trim(entryParts[0]); String value = StringUtils.trim(entryParts[1]); value = StringUtils.removeStart(value, "\""); value = StringUtils.removeEnd(value, "\""); try { if ("offset".equalsIgnoreCase(key)) { helper.getClass().getDeclaredField(key).set(helper, Integer.valueOf(value.toString())); } else { helper.getClass().getDeclaredField(key).set(helper, value); } } catch (Exception e) { throw new BindingConfigParseException("Could not set value " + value + " for attribute " + key); } } if (helper.isOldStyle()) { logger.warn( "Old Astro binding style for item {}, please see Wiki page for new style: https://github.com/openhab/openhab/wiki/Astro-binding", item.getName()); return getOldAstroBindingConfig(helper); } if (!helper.isValid()) { throw new BindingConfigParseException("Invalid binding: " + bindingConfig); } PlanetName planetName = getPlanetName(helper); if (planetName == null) { throw new BindingConfigParseException("Invalid binding, unknown planet: " + bindingConfig); } AstroBindingConfig astroConfig = new AstroBindingConfig(planetName, helper.type, helper.property, helper.offset); if (!PropertyUtils.hasProperty(context.getPlanet(astroConfig.getPlanetName()), astroConfig.getPlanetProperty())) { throw new BindingConfigParseException("Invalid binding, unknown type or property: " + bindingConfig); } return astroConfig; }
From source file:org.openhab.binding.homematic.handler.HomematicThingHandler.java
/** * {@inheritDoc}/*from w w w .java 2 s.c om*/ */ @Override public void handleConfigurationUpdate(Map<String, Object> configurationParameters) throws ConfigValidationException { validateConfigurationParameters(configurationParameters); try { HomematicGateway gateway = getHomematicGateway(); HmDevice device = gateway.getDevice(UidUtils.getHomematicAddress(getThing())); for (Entry<String, Object> configurationParmeter : configurationParameters.entrySet()) { String key = configurationParmeter.getKey(); Object newValue = configurationParmeter.getValue(); if (key.startsWith("HMP_")) { key = StringUtils.removeStart(key, "HMP_"); Integer channelNumber = NumberUtils.toInt(StringUtils.substringBefore(key, "_")); String dpName = StringUtils.substringAfter(key, "_"); HmDatapointInfo dpInfo = new HmDatapointInfo(device.getAddress(), HmParamsetType.MASTER, channelNumber, dpName); HmDatapoint dp = device.getChannel(channelNumber).getDatapoint(dpInfo); if (dp != null) { try { if (newValue != null) { if (newValue instanceof BigDecimal) { final BigDecimal decimal = (BigDecimal) newValue; if (dp.isIntegerType()) { newValue = decimal.intValue(); } else if (dp.isFloatType()) { newValue = decimal.doubleValue(); } } if (ObjectUtils.notEqual(dp.isEnumType() ? dp.getOptionValue() : dp.getValue(), newValue)) { gateway.sendDatapoint(dp, new HmDatapointConfig(), newValue); } } } catch (IOException ex) { logger.error("Error setting thing property {}: {}", dpInfo, ex.getMessage()); } } else { logger.error("Can't find datapoint for thing property {}", dpInfo); } } } gateway.triggerDeviceValuesReload(device); } catch (HomematicClientException | BridgeHandlerNotAvailableException ex) { logger.error("Error setting thing properties: {}", ex.getMessage(), ex); } }
From source file:org.openhab.binding.homematic.internal.bus.BindingConfigParser.java
/** * Parses the bindingConfig of an item and returns a HomematicBindingConfig. *///from w w w .jav a 2s .co m public HomematicBindingConfig parse(Item item, String bindingConfig) throws BindingConfigParseException { bindingConfig = StringUtils.trimToEmpty(bindingConfig); bindingConfig = StringUtils.removeStart(bindingConfig, "{"); bindingConfig = StringUtils.removeEnd(bindingConfig, "}"); String[] entries = bindingConfig.split("[,]"); HomematicBindingConfigHelper helper = new HomematicBindingConfigHelper(); for (String entry : entries) { String[] entryParts = StringUtils.trimToEmpty(entry).split("[=]"); if (entryParts.length != 2) { throw new BindingConfigParseException("Each entry must have a key and a value"); } String key = StringUtils.trim(entryParts[0]); // convert entry id to device if necessary if ("id".equalsIgnoreCase(key)) { logger.info("Please change the Homematic binding with the attribute 'id' to 'address' in entry: " + entry + " -> " + StringUtils.replace(entry, "id=", "address=")); key = "address"; } String value = StringUtils.trim(entryParts[1]); value = StringUtils.removeStart(value, "\""); value = StringUtils.removeEnd(value, "\""); try { helper.getClass().getDeclaredField(key).set(helper, value); } catch (Exception e) { throw new BindingConfigParseException("Could not set value " + value + " for attribute " + key); } } Converter<?> converter = null; // if (helper.isValidDatapoint() || helper.isValidVariable()) { // converter = instantiateConverter(helper.converter); // } BindingAction bindingAction = getBindingAction(item, helper.action); if (helper.isValidDatapoint()) { return new DatapointConfig(helper.address, helper.channel, helper.parameter, converter, bindingAction, helper.isForceUpdate(), NumberUtils.toDouble(helper.delay)); } else if (helper.isValidVariable()) { return new VariableConfig(helper.variable, converter, bindingAction, helper.isForceUpdate(), NumberUtils.toDouble(helper.delay)); } else if (helper.isValidProgram()) { if (!acceptsOnOffType(item)) { throw new BindingConfigParseException( "Programs can only be attached to items which accepts OnOffType commands, ignoring item " + item.getName()); } return new ProgramConfig(helper.program, bindingAction); } else if (bindingAction != null) { return new ActionConfig(bindingAction); } else { throw new BindingConfigParseException("Invalid binding: " + bindingConfig); } }
From source file:org.openhab.binding.weather.internal.bus.BindingConfigParser.java
/** * Parses the bindingConfig of an item and returns a WeatherBindingConfig. *///from w w w . ja va 2 s.c o m public WeatherBindingConfig parse(Item item, String bindingConfig) throws BindingConfigParseException { bindingConfig = StringUtils.trimToEmpty(bindingConfig); bindingConfig = StringUtils.removeStart(bindingConfig, "{"); bindingConfig = StringUtils.removeEnd(bindingConfig, "}"); String[] entries = bindingConfig.split("[,]"); WeatherBindingConfigHelper helper = new WeatherBindingConfigHelper(); for (String entry : entries) { String[] entryParts = StringUtils.trimToEmpty(entry).split("[=]"); if (entryParts.length != 2) { throw new BindingConfigParseException("A bindingConfig must have a key and a value"); } String key = StringUtils.trim(entryParts[0]); String value = StringUtils.trim(entryParts[1]); value = StringUtils.removeStart(value, "\""); value = StringUtils.removeEnd(value, "\""); try { helper.getClass().getDeclaredField(key).set(helper, value); } catch (Exception e) { throw new BindingConfigParseException("Could not set value " + value + " for attribute " + key); } } if (!helper.isValid()) { throw new BindingConfigParseException("Invalid binding: " + bindingConfig); } helper.type = StringUtils.replace(helper.type, "athmosphere", "atmosphere"); WeatherBindingConfig weatherConfig = null; if (helper.isForecast()) { Integer forecast = parseInteger(helper.forecast, bindingConfig); if (forecast < 0) { throw new BindingConfigParseException("Invalid binding, forecast must be >= 0: " + bindingConfig); } weatherConfig = new ForecastBindingConfig(helper.locationId, forecast, helper.type, helper.property); } else { weatherConfig = new WeatherBindingConfig(helper.locationId, helper.type, helper.property); } Weather validationInstance = new Weather(null); String property = weatherConfig.getWeatherProperty(); if (!Weather.isVirtualProperty(property) && !PropertyUtils.hasProperty(validationInstance, property)) { throw new BindingConfigParseException("Invalid binding, unknown type or property: " + bindingConfig); } boolean isDecimalTypeItem = item.getAcceptedDataTypes().contains(DecimalType.class); if (isDecimalTypeItem || Weather.isVirtualProperty(property)) { RoundingMode roundingMode = RoundingMode.HALF_UP; if (helper.roundingMode != null) { try { roundingMode = RoundingMode.valueOf(StringUtils.upperCase(helper.roundingMode)); } catch (IllegalArgumentException ex) { throw new BindingConfigParseException( "Invalid binding, unknown roundingMode: " + bindingConfig); } } Integer scale = 2; if (helper.scale != null) { scale = parseInteger(helper.scale, bindingConfig); if (scale < 0) { throw new BindingConfigParseException("Invalid binding, scale must be >= 0: " + bindingConfig); } } weatherConfig.setScale(roundingMode, scale); } weatherConfig.setUnit(Unit.parse(helper.unit)); if (StringUtils.isNotBlank(helper.unit) && weatherConfig.getUnit() == null) { throw new BindingConfigParseException("Invalid binding, unknown unit: " + bindingConfig); } try { if (!Weather.isVirtualProperty(property) && weatherConfig.hasUnit()) { String doubleTypeName = Double.class.getName(); String propertyTypeName = PropertyUtils.getPropertyTypeName(validationInstance, property); if (!StringUtils.equals(doubleTypeName, propertyTypeName)) { throw new BindingConfigParseException( "Invalid binding, unit specified but property is not a double type: " + bindingConfig); } } } catch (IllegalAccessException ex) { logger.error(ex.getMessage(), ex); throw new BindingConfigParseException(ex.getMessage()); } return weatherConfig; }
From source file:org.opennms.netmgt.provision.service.dns.DnsRequisitionUrlConnection.java
/** * Validate the format is:// w w w. j a va2 s . c o m * dns://<host>/<zone>/?expression=<regex> * * there should be only one arguement in the path * there should only be one query parameter * * @param url a {@link java.net.URL} object. * @throws java.net.MalformedURLException if any. */ protected static void validateDnsUrl(URL url) throws MalformedURLException { String path = url.getPath(); path = StringUtils.removeStart(path, "/"); path = StringUtils.removeEnd(path, "/"); if (path == null || StringUtils.countMatches(path, "/") > 1) { throw new MalformedURLException("The specified DNS URL contains invalid path: " + url); } String query = url.getQuery(); if ((query != null) && (determineExpressionFromUrl(url) == null) && (getArgs().get(SERVICES_ARG) == null) && (getArgs().get(FID_HASH_SRC_ARG) == null)) { throw new MalformedURLException("The specified DNS URL contains an invalid query string: " + url); } }
From source file:org.opennms.netmgt.provision.service.dns.DnsRequisitionUrlConnection.java
/** * Zone should be the first path entity//from ww w .ja v a 2 s . c o m * * dns://<host>/<zone>[/<foreign source>][/<?expression=<regex>> * * @param url a {@link java.net.URL} object. * @return a {@link java.lang.String} object. */ protected static String parseZone(URL url) { String path = url.getPath(); path = StringUtils.removeStart(path, "/"); path = StringUtils.removeEnd(path, "/"); String zone = path; if (path != null && StringUtils.countMatches(path, "/") == 1) { String[] paths = path.split("/"); zone = paths[0]; } return zone; }
From source file:org.opennms.netmgt.provision.service.dns.DnsRequisitionUrlConnection.java
/** * Foreign Source should be the second path entity, if it exists, otherwise it is * set to the value of the zone./*from ww w . j a v a2s . c om*/ * * dns://<host>/<zone>[/<foreign source>][/<?expression=<regex>> * * @param url a {@link java.net.URL} object. * @return a {@link java.lang.String} object. */ protected static String parseForeignSource(URL url) { String path = url.getPath(); path = StringUtils.removeStart(path, "/"); path = StringUtils.removeEnd(path, "/"); String foreignSource = path; if (path != null && StringUtils.countMatches(path, "/") == 1) { String[] paths = path.split("/"); foreignSource = paths[1]; } return foreignSource; }
From source file:org.opennms.netmgt.provision.service.vmware.VmwareRequisitionUrlConnection.java
/** * Checks whether an attribute/value is defined by a managed entity. * /*from www .j a va 2 s. c o m*/ * <p>The old implementation allows the user to specify only one parameter.</p> * <p>The new implementation allows the user to use a regular expression for the value:</p> * <ul><li>key=location&value=~North.*</li></ul> * <p>As an alternative, now it is possible to specify several parameters on the query. * The rule is to add an underscore character ('_') before the patameter's name and use similar rules for the value:</p> * <ul><li>_location=~North.*</li></ul> * <p>With the new parameter specification, it is possible to pass several attributes. The managed entity must match * all of them to be accepted.</p> * <p>The new specification will take precedence over the old specification. If the new specification is not being used, * the old one will be processed. Otherwise, the new one will be processed, and the old one will be ignored. There is no * way to use both at the same time.</p> * * @param managedEntity the managed entity to check * @return true if present and value is equal, false otherwise * @throws RemoteException */ private boolean checkForAttribute(ManagedEntity managedEntity) throws RemoteException { logger.debug("Getting custom attributes from VMware management server {} : ManagedEntity {} (ID: {})", m_hostname, managedEntity.getName(), managedEntity.getMOR().getVal()); Map<String, String> attribMap = getCustomAttributes(managedEntity); Set<String> keySet = new TreeSet<String>(); for (String k : m_args.keySet()) { if (k.startsWith("_")) { keySet.add(k); } } if (!keySet.isEmpty()) { boolean ok = true; for (String keyName : keySet) { String attribValue = attribMap.get(StringUtils.removeStart(keyName, "_")); if (attribValue == null) { ok = false; } else { String keyValue = m_args.get(keyName); if (keyValue.startsWith("~")) { ok = ok && attribValue.matches(StringUtils.removeStart(keyValue, "~")); } else { ok = ok && attribValue.equals(keyValue); } } } return ok; } String key = m_args.get("key"); String value = m_args.get("value"); // if key/value is not set, return true if (key == null && value == null) { return true; } // if only key or value is set, return false if (key == null || value == null) { return false; } // now search for the correct key/value pair String attribValue = attribMap.get(key); if (attribValue != null) { if (value.startsWith("~")) { return attribValue.matches(StringUtils.removeStart(value, "~")); } else { return attribValue.equals(value); } } return false; }