下面列出了org.springframework.util.StringUtils#replace ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static String inSQL(Object value) {
if (value == null) {
return "NULL";
}
Class<?> aClass = value.getClass();
if (ClassUtils.isPrimitiveOrWrapper(aClass)
|| CharSequence.class.isAssignableFrom(aClass)
|| value instanceof Timestamp
|| value instanceof BigDecimal) {
if (value instanceof String) {
// TODO 2019/3/3 http://www.jguru.com/faq/view.jsp?EID=8881 {escape '/'} ?
String replace = StringUtils.replace(StringUtils.replace(value.toString(), "'", "''"), "\\", "\\\\");
value = "'" + replace + "'";
} else if (value instanceof Timestamp) {
value = "'" + value.toString() + "'";
}
} else if (SQLFunction.class.isAssignableFrom(aClass)) {
value = value.toString();
} else {
logger.error("Unhandled complex type: {}, value: {}", aClass, value);
}
return value.toString();
}
/**
* Get label for data dictionary item given specified locale
*
* @param locale Locale
* @param model ModelDefinition
* @param messageLookup MessageLookup
* @param type String
* @param item QName
* @param label String
* @return String
*/
public static String getLabel(Locale locale, ModelDefinition model, MessageLookup messageLookup, String type, QName item, String label)
{
if (messageLookup == null)
{
return null;
}
String key = model.getName().toPrefixString();
if (type != null)
{
key += "." + type;
}
if (item != null)
{
key += "." + item.toPrefixString();
}
key += "." + label;
key = StringUtils.replace(key, ":", "_");
return messageLookup.getMessage(key, locale);
}
private Class<?> doLoadClass(String name) throws ClassNotFoundException {
String internalName = StringUtils.replace(name, ".", "/") + ".class";
InputStream is = this.enclosingClassLoader.getResourceAsStream(internalName);
if (is == null) {
throw new ClassNotFoundException(name);
}
try {
byte[] bytes = FileCopyUtils.copyToByteArray(is);
bytes = applyTransformers(name, bytes);
Class<?> cls = defineClass(name, bytes, 0, bytes.length);
// Additional check for defining the package, if not defined yet.
if (cls.getPackage() == null) {
int packageSeparator = name.lastIndexOf('.');
if (packageSeparator != -1) {
String packageName = name.substring(0, packageSeparator);
definePackage(packageName, null, null, null, null, null, null, null);
}
}
this.classCache.put(name, cls);
return cls;
}
catch (IOException ex) {
throw new ClassNotFoundException("Cannot load resource for class [" + name + "]", ex);
}
}
private ParseResult parseMessage(MessageHeaders headers, String sourceDest) {
int prefixEnd = this.prefix.length();
int userEnd = sourceDest.indexOf('/', prefixEnd);
Assert.isTrue(userEnd > 0, "Expected destination pattern \"/user/{userId}/**\"");
String actualDest = sourceDest.substring(userEnd);
String subscribeDest = this.prefix.substring(0, prefixEnd - 1) + actualDest;
String userName = sourceDest.substring(prefixEnd, userEnd);
userName = StringUtils.replace(userName, "%2F", "/");
String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
Set<String> sessionIds;
if (userName.equals(sessionId)) {
userName = null;
sessionIds = Collections.singleton(sessionId);
}
else {
sessionIds = getSessionIdsByUser(userName, sessionId);
}
if (isRemoveLeadingSlash()) {
actualDest = actualDest.substring(1);
}
return new ParseResult(sourceDest, actualDest, subscribeDest, sessionIds, userName);
}
/**
* Transform the request URI (in the context of the webapp) stripping
* slashes and extensions, and replacing the separator as required.
* @param lookupPath the lookup path for the current request,
* as determined by the UrlPathHelper
* @return the transformed path, with slashes and extensions stripped
* if desired
*/
protected String transformPath(String lookupPath) {
String path = lookupPath;
if (this.stripLeadingSlash && path.startsWith(SLASH)) {
path = path.substring(1);
}
if (this.stripTrailingSlash && path.endsWith(SLASH)) {
path = path.substring(0, path.length() - 1);
}
if (this.stripExtension) {
path = StringUtils.stripFilenameExtension(path);
}
if (!SLASH.equals(this.separator)) {
path = StringUtils.replace(path, SLASH, this.separator);
}
return path;
}
@Override
public void nodeChanged(String node, String value) {
String genericNodeName = StringUtils.replace(node, PREFIX, "");
if(nodeListeners.get(genericNodeName).isEmpty()){
logger.warn("Couldn't find listener to tell about zk node change: " + node + " -> " + value);
}
for (GlobalConfigUpdateListener list : nodeListeners.get(genericNodeName)){
list.configUpdated(genericNodeName, value);
}
}
/**
* If a pointcut expression has been specified in XML, the user cannot
* write {@code and} as "&&" (though && will work).
* We also allow {@code and} between two pointcut sub-expressions.
* <p>This method converts back to {@code &&} for the AspectJ pointcut parser.
*/
private String replaceBooleanOperators(String pcExpr) {
String result = StringUtils.replace(pcExpr, " and ", " && ");
result = StringUtils.replace(result, " or ", " || ");
result = StringUtils.replace(result, " not ", " ! ");
return result;
}
/**
* Replace the values in the comma-separated list (case insensitive)
* with their index in the list.
* @return a new String with the values from the list replaced
*/
private String replaceOrdinals(String value, String commaSeparatedList) {
String[] list = StringUtils.commaDelimitedListToStringArray(commaSeparatedList);
for (int i = 0; i < list.length; i++) {
String item = list[i].toUpperCase();
value = StringUtils.replace(value.toUpperCase(), item, "" + i);
}
return value;
}
/**
* Replace the values in the comma-separated list (case insensitive)
* with their index in the list.
* @return a new String with the values from the list replaced
*/
private String replaceOrdinals(String value, String commaSeparatedList) {
String[] list = StringUtils.commaDelimitedListToStringArray(commaSeparatedList);
for (int i = 0; i < list.length; i++) {
String item = list[i].toUpperCase();
value = StringUtils.replace(value.toUpperCase(), item, "" + i);
}
return value;
}
private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
// Retrieve and parse cookie value.
Cookie cookie = WebUtils.getCookie(request, getCookieName());
Locale locale = null;
TimeZone timeZone = null;
if (cookie != null) {
String value = cookie.getValue();
// Remove the double quote
value = StringUtils.replace(value, "%22", "");
String localePart = value;
String timeZonePart = null;
int spaceIndex = localePart.indexOf(' ');
if (spaceIndex != -1) {
localePart = value.substring(0, spaceIndex);
timeZonePart = value.substring(spaceIndex + 1);
}
locale = (!"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null);
if (timeZonePart != null) {
timeZone = StringUtils.parseTimeZoneString(timeZonePart);
}
if (logger.isTraceEnabled()) {
logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale +
"'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
}
}
request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
(locale != null ? locale: determineDefaultLocale(request)));
request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
(timeZone != null ? timeZone : determineDefaultTimeZone(request)));
}
}
private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
// Retrieve and parse cookie value.
Cookie cookie = WebUtils.getCookie(request, getCookieName());
Locale locale = null;
TimeZone timeZone = null;
if (cookie != null) {
String value = cookie.getValue();
// Remove the double quote
value = StringUtils.replace(value, "%22", "");
String localePart = value;
String timeZonePart = null;
int spaceIndex = localePart.indexOf(' ');
if (spaceIndex != -1) {
localePart = value.substring(0, spaceIndex);
timeZonePart = value.substring(spaceIndex + 1);
}
locale = (!"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null);
if (timeZonePart != null) {
timeZone = StringUtils.parseTimeZoneString(timeZonePart);
}
if (logger.isTraceEnabled()) {
logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale +
"'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
}
}
request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
(locale != null ? locale: determineDefaultLocale(request)));
request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
(timeZone != null ? timeZone : determineDefaultTimeZone(request)));
}
}
/**
* Retrieve files that match the given path pattern,
* checking the given directory and its subdirectories.
* @param rootDir the directory to start from
* @param pattern the pattern to match against,
* relative to the root directory
* @return a mutable Set of matching Resource instances
* @throws IOException if directory contents could not be retrieved
*/
protected Set<File> retrieveMatchingFiles(File rootDir, String pattern) throws IOException {
if (!rootDir.exists()) {
// Silently skip non-existing directories.
if (logger.isDebugEnabled()) {
logger.debug("Skipping [" + rootDir.getAbsolutePath() + "] because it does not exist");
}
return Collections.emptySet();
}
if (!rootDir.isDirectory()) {
// Complain louder if it exists but is no directory.
if (logger.isWarnEnabled()) {
logger.warn("Skipping [" + rootDir.getAbsolutePath() + "] because it does not denote a directory");
}
return Collections.emptySet();
}
if (!rootDir.canRead()) {
if (logger.isWarnEnabled()) {
logger.warn("Cannot search for matching files underneath directory [" + rootDir.getAbsolutePath() +
"] because the application is not allowed to read the directory");
}
return Collections.emptySet();
}
String fullPattern = StringUtils.replace(rootDir.getAbsolutePath(), File.separator, "/");
if (!pattern.startsWith("/")) {
fullPattern += "/";
}
fullPattern = fullPattern + StringUtils.replace(pattern, File.separator, "/");
Set<File> result = new LinkedHashSet<File>(8);
doRetrieveMatchingFiles(fullPattern, rootDir, result);
return result;
}
private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
// Retrieve and parse cookie value.
Cookie cookie = WebUtils.getCookie(request, getCookieName());
Locale locale = null;
TimeZone timeZone = null;
if (cookie != null) {
String value = cookie.getValue();
// Remove the double quote
value = StringUtils.replace(value, "%22", "");
String localePart = value;
String timeZonePart = null;
int spaceIndex = localePart.indexOf(' ');
if (spaceIndex != -1) {
localePart = value.substring(0, spaceIndex);
timeZonePart = value.substring(spaceIndex + 1);
}
locale = (!"-".equals(localePart) ? StringUtils.parseLocaleString(localePart.replace('-', '_')) : null);
if (timeZonePart != null) {
timeZone = StringUtils.parseTimeZoneString(timeZonePart);
}
if (logger.isTraceEnabled()) {
logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale +
"'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
}
}
request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
(locale != null ? locale: determineDefaultLocale(request)));
request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
(timeZone != null ? timeZone : determineDefaultTimeZone(request)));
}
}
private void runPreValidateModeCommands(Properties props) throws Exception {
// pre-validate command and environment vars
String preValCmd = props.getProperty("worker.pre.validate.cmd");
String preValCmdEnv = props.getProperty("worker.pre.validate.cmd.env");
// note that either of these can reference %worker.initialize.cmd% and/or %worker.initialize.cmd.env%
// so we will replace them if present
preValCmd = StringUtils.replace(preValCmd, "%worker.initialize.cmd%", props.getProperty("worker.initialize.cmd"));
preValCmdEnv = StringUtils.replace(preValCmdEnv, "%worker.initialize.cmd.env%", props.getProperty("worker.initialize.cmd.env"));
if (preValCmd != null) {
Map<String,String> env = null;
if (preValCmdEnv != null) {
env = Splitter.on(",").withKeyValueSeparator("=").split(preValCmdEnv);
}
// preValCmd can have multiple delimited by ;
List<String> cmdsToRun = new ArrayList<String>();
if (preValCmd.indexOf(";") != -1) {
cmdsToRun.addAll(Arrays.asList(preValCmd.split(";")));
}
for (String cmd : cmdsToRun) {
// execute it!
logger.debug("Running pre.validate command: " + cmd);
CommandLine cmdLine = CommandLine.parse(cmd);
DefaultExecutor executor = new DefaultExecutor();
executor.execute(cmdLine, env);
}
}
}
/**
* If a pointcut expression has been specified in XML, the user cannot
* write {@code and} as "&&" (though && will work).
* We also allow {@code and} between two pointcut sub-expressions.
* <p>This method converts back to {@code &&} for the AspectJ pointcut parser.
*/
private String replaceBooleanOperators(String pcExpr) {
String result = StringUtils.replace(pcExpr, " and ", " && ");
result = StringUtils.replace(result, " or ", " || ");
result = StringUtils.replace(result, " not ", " ! ");
return result;
}
@Override
public void convertAndSendToUser(String user, String destination, Object payload,
@Nullable Map<String, Object> headers, @Nullable MessagePostProcessor postProcessor)
throws MessagingException {
Assert.notNull(user, "User must not be null");
user = StringUtils.replace(user, "/", "%2F");
destination = destination.startsWith("/") ? destination : "/" + destination;
super.convertAndSend(this.destinationPrefix + user + destination, payload, headers, postProcessor);
}
/**
* Get the display label for the specified allowable value in this constraint.
* A key is constructed as follows:
* <pre>
* "listconstraint." + constraintName + "." + constraintAllowableValue.
* e.g. listconstraint.test_listConstraintOne.VALUE_ONE.
* </pre>
* This key is then used to look up a properties bundle for the localised display label.
* Spaces are allowed in the keys, but they should be escaped in the properties file as follows:
* <pre>
* listconstraint.test_listConstraintOne.VALUE\ WITH\ SPACES=Display label
* </pre>
*
* @param constraintAllowableValue String
* @param messageLookup MessageLookup
* @return the localised display label for the specified constraint value in the current locale.
* If no localisation is defined, it will return the allowed value itself.
* If the specified allowable value is not in the model, returns <code>null</code>.
* @since 4.0
* @see I18NUtil#getLocale()
*/
public String getDisplayLabel(String constraintAllowableValue, MessageLookup messageLookup)
{
if (!allowedValues.contains(constraintAllowableValue))
{
return null;
}
String key = LOV_CONSTRAINT_VALUE;
key += "." + this.getShortName();
key += "." + constraintAllowableValue;
key = StringUtils.replace(key, ":", "_");
String message = messageLookup.getMessage(key, I18NUtil.getLocale());
return message == null ? constraintAllowableValue : message;
}
private String getQuery(String base) {
return StringUtils.replace(base, "%PREFIX%", this.tablePrefix);
}
/**
* If a type pattern has been specified in XML, the user cannot
* write {@code and} as "&&" (though && will work).
* We also allow {@code and} between two sub-expressions.
* <p>This method converts back to {@code &&} for the AspectJ pointcut parser.
*/
private String replaceBooleanOperators(String pcExpr) {
String result = StringUtils.replace(pcExpr," and "," && ");
result = StringUtils.replace(result, " or ", " || ");
return StringUtils.replace(result, " not ", " ! ");
}
/**
* Process the given resource path.
* <p>The default implementation replaces:
* <ul>
* <li>Backslash with forward slash.
* <li>Duplicate occurrences of slash with a single slash.
* <li>Any combination of leading slash and control characters (00-1F and 7F)
* with a single "/" or "". For example {@code " / // foo/bar"}
* becomes {@code "/foo/bar"}.
* </ul>
* @since 3.2.12
*/
protected String processPath(String path) {
path = StringUtils.replace(path, "\\", "/");
path = cleanDuplicateSlashes(path);
return cleanLeadingSlash(path);
}