1、解析字符串中路径变量
private static final AntPathMatcher MATCHER = new AntPathMatcher();
/**
* 解析 topic 模板中的变量 例如 $SYS/brokers/${node}/clients/${clientid}/disconnected 中提取 node 和 clientid
*
* @param topicTemplate topicTemplate
* @param topic topic
* @return 提取的变量
*/
public static Map<String, String> extractTopicValue(String topicTemplate, String topic){
String pattern = topicTemplate.replace("${", "{").replace("#{", "{");
try {
return MATCHER.extractUriTemplateVariables(pattern, topic);
} catch (IllegalStateException e) {
return Collections.emptyMap();
}
}
public static void main(String[] args) {
System.out.println(extractTopicValue("tlink/${productKey}/${deviceName}/**", "tlink/123/456/command/setProperty/post"));
}
运行结果:
2、获取jar包运行时目录
package com.talkweb.twiot.iothub.utils;
import cn.hutool.core.util.URLUtil;
import lombok.experimental.UtilityClass;
import org.springframework.lang.Nullable;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.net.URL;
import java.nio.charset.StandardCharsets;
@UtilityClass
public class PathUtil {
/**
* 获取jar包运行时的当前目录
*
* @return {String}
*/
@Nullable
public static String getJarPath() {
try {
URL url = PathUtil.class.getResource("/").toURI().toURL();
return PathUtil.toFilePath(url);
} catch (Exception e) {
String path = PathUtil.class.getResource("").getPath();
return new File(path).getParentFile().getParentFile().getAbsolutePath();
}
}
@Nullable
private static String toFilePath(@Nullable URL url) {
if (url == null) {
return null;
}
String protocol = url.getProtocol();
String file = URLUtil.decode(url.getPath(), StandardCharsets.UTF_8);
if (ResourceUtils.URL_PROTOCOL_FILE.equals(protocol)) {
return new File(file).getParentFile().getParentFile().getAbsolutePath();
} else if (ResourceUtils.URL_PROTOCOL_JAR.equals(protocol) || ResourceUtils.URL_PROTOCOL_ZIP.equals(protocol)) {
int ipos = file.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
if (ipos > 0) {
file = file.substring(0, ipos);
}
if (file.startsWith(ResourceUtils.FILE_URL_PREFIX)) {
file = file.substring(ResourceUtils.FILE_URL_PREFIX.length());
}
return new File(file).getParentFile().getAbsolutePath();
}
return file;
}
public static void main(String[] args) {
getJarPath();
}
}