repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/LogUtilTest.java
core/src/test/java/com/taobao/arthas/core/util/LogUtilTest.java
package com.taobao.arthas.core.util; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.Iterator; import java.util.Properties; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.alibaba.arthas.deps.ch.qos.logback.classic.Level; import com.alibaba.arthas.deps.ch.qos.logback.classic.Logger; import com.alibaba.arthas.deps.ch.qos.logback.classic.LoggerContext; import com.alibaba.arthas.deps.ch.qos.logback.classic.spi.ILoggingEvent; import com.alibaba.arthas.deps.ch.qos.logback.core.Appender; import com.alibaba.arthas.deps.ch.qos.logback.core.rolling.RollingFileAppender; import com.taobao.arthas.core.env.ArthasEnvironment; import com.taobao.arthas.core.env.PropertiesPropertySource; /** * * @author hengyunabc * */ public class LogUtilTest { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); ArthasEnvironment arthasEnvironment; String testResourcesDir; @Before public void before() throws URISyntaxException { ClassLoader classLoader = LogUtilTest.class.getClassLoader(); String logbakXmlPath = classLoader.getResource("logback-test.xml").toURI().getPath(); testResourcesDir = new File(logbakXmlPath).getParent(); arthasEnvironment = new ArthasEnvironment(); } @Test public void testArthasHome() throws URISyntaxException { Properties properties1 = new Properties(); properties1.put("arthas.home", testResourcesDir); arthasEnvironment.addLast(new PropertiesPropertySource("test1", properties1)); LoggerContext loggerContext = LogUtil.initLogger(arthasEnvironment); Logger logger = loggerContext.getLogger("root"); Level level = logger.getLevel(); Assertions.assertThat(level).isEqualTo(Level.ERROR); } @Test public void testLogConfig() throws URISyntaxException { Properties properties1 = new Properties(); properties1.put("arthas.home", testResourcesDir); properties1.put(LogUtil.LOGGING_CONFIG_PROPERTY, testResourcesDir + "/logback-test.xml"); arthasEnvironment.addLast(new PropertiesPropertySource("test1", properties1)); LoggerContext loggerContext = LogUtil.initLogger(arthasEnvironment); Logger logger = loggerContext.getLogger("root"); Level level = logger.getLevel(); Assertions.assertThat(level).isEqualTo(Level.WARN); } @Test public void test_DefaultLogFile() throws URISyntaxException, IOException { Properties properties1 = new Properties(); properties1.put("arthas.home", testResourcesDir); String logFile = new File(System.getProperty("user.home"), "logs/arthas/arthas.log").getCanonicalPath(); arthasEnvironment.addLast(new PropertiesPropertySource("test1", properties1)); LoggerContext loggerContext = LogUtil.initLogger(arthasEnvironment); Logger logger = loggerContext.getLogger("root"); Level level = logger.getLevel(); Assertions.assertThat(level).isEqualTo(Level.ERROR); Iterator<Appender<ILoggingEvent>> appenders = logger.iteratorForAppenders(); boolean foundFileAppender = false; while (appenders.hasNext()) { Appender<ILoggingEvent> appender = appenders.next(); if (appender instanceof RollingFileAppender) { RollingFileAppender fileAppender = (RollingFileAppender) appender; String file = fileAppender.getFile(); Assertions.assertThat(new File(file).getCanonicalPath()).isEqualTo(logFile); foundFileAppender = true; } } Assertions.assertThat(foundFileAppender).isEqualTo(true); } @Test public void test_ARTHAS_LOG_FILE() throws URISyntaxException, IOException { Properties properties1 = new Properties(); properties1.put("arthas.home", testResourcesDir); String logFile = new File(tempFolder.getRoot().getAbsoluteFile(), "test.log").getCanonicalPath(); properties1.put(LogUtil.FILE_NAME_PROPERTY, logFile); arthasEnvironment.addLast(new PropertiesPropertySource("test1", properties1)); LoggerContext loggerContext = LogUtil.initLogger(arthasEnvironment); Logger logger = loggerContext.getLogger("root"); Level level = logger.getLevel(); Assertions.assertThat(level).isEqualTo(Level.ERROR); Iterator<Appender<ILoggingEvent>> appenders = logger.iteratorForAppenders(); boolean foundFileAppender = false; while (appenders.hasNext()) { Appender<ILoggingEvent> appender = appenders.next(); if (appender instanceof RollingFileAppender) { RollingFileAppender fileAppender = (RollingFileAppender) appender; String file = fileAppender.getFile(); Assertions.assertThat(new File(file).getCanonicalPath()).isEqualTo(logFile); foundFileAppender = true; } } Assertions.assertThat(foundFileAppender).isEqualTo(true); } @Test public void test_ARTHAS_LOG_PATH() throws URISyntaxException, IOException { Properties properties1 = new Properties(); properties1.put("arthas.home", testResourcesDir); String logFile = new File(tempFolder.getRoot().getAbsoluteFile(), "arthas.log").getCanonicalPath(); properties1.put(LogUtil.FILE_PATH_PROPERTY, tempFolder.getRoot().getAbsolutePath()); arthasEnvironment.addLast(new PropertiesPropertySource("test1", properties1)); LoggerContext loggerContext = LogUtil.initLogger(arthasEnvironment); Logger logger = loggerContext.getLogger("root"); Level level = logger.getLevel(); Assertions.assertThat(level).isEqualTo(Level.ERROR); Iterator<Appender<ILoggingEvent>> appenders = logger.iteratorForAppenders(); boolean foundFileAppender = false; while (appenders.hasNext()) { Appender<ILoggingEvent> appender = appenders.next(); if (appender instanceof RollingFileAppender) { RollingFileAppender fileAppender = (RollingFileAppender) appender; String file = fileAppender.getFile(); Assertions.assertThat(new File(file).getCanonicalPath()).isEqualTo(logFile); foundFileAppender = true; } } Assertions.assertThat(foundFileAppender).isEqualTo(true); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/LongStackTest.java
core/src/test/java/com/taobao/arthas/core/util/LongStackTest.java
package com.taobao.arthas.core.util; import org.junit.Assert; import org.junit.Test; /** * * @author hengyunabc 2019-11-20 * */ public class LongStackTest { @Test public void test() { long[] stack = new long[101]; ThreadLocalWatch.push(stack, 1); ThreadLocalWatch.push(stack, 2); ThreadLocalWatch.push(stack, 3); Assert.assertEquals(3, ThreadLocalWatch.pop(stack)); Assert.assertEquals(2, ThreadLocalWatch.pop(stack)); Assert.assertEquals(1, ThreadLocalWatch.pop(stack)); } @Test public void test2() { long[] stack = new long[101]; ThreadLocalWatch.push(stack, 1); ThreadLocalWatch.push(stack, 2); ThreadLocalWatch.push(stack, 3); Assert.assertEquals(3, ThreadLocalWatch.pop(stack)); Assert.assertEquals(2, ThreadLocalWatch.pop(stack)); Assert.assertEquals(1, ThreadLocalWatch.pop(stack)); Assert.assertEquals(0, ThreadLocalWatch.pop(stack)); } @Test public void test3() { long[] stack = new long[3]; ThreadLocalWatch.push(stack, 1); ThreadLocalWatch.push(stack, 2); ThreadLocalWatch.push(stack, 3); Assert.assertEquals(3, ThreadLocalWatch.pop(stack)); Assert.assertEquals(2, ThreadLocalWatch.pop(stack)); Assert.assertEquals(3, ThreadLocalWatch.pop(stack)); Assert.assertEquals(2, ThreadLocalWatch.pop(stack)); } @Test public void test4() { long[] stack = new long[3]; ThreadLocalWatch.push(stack, 1); ThreadLocalWatch.push(stack, 2); Assert.assertEquals(2, ThreadLocalWatch.pop(stack)); Assert.assertEquals(1, ThreadLocalWatch.pop(stack)); Assert.assertEquals(2, ThreadLocalWatch.pop(stack)); Assert.assertEquals(1, ThreadLocalWatch.pop(stack)); } @Test public void test5() { long[] stack = new long[11]; ThreadLocalWatch.push(stack, 1); ThreadLocalWatch.push(stack, 2); ThreadLocalWatch.push(stack, 3); ThreadLocalWatch.pop(stack); ThreadLocalWatch.pop(stack); ThreadLocalWatch.push(stack, 4); ThreadLocalWatch.push(stack, 5); ThreadLocalWatch.push(stack, 6); ThreadLocalWatch.pop(stack); Assert.assertEquals(5, ThreadLocalWatch.pop(stack)); Assert.assertEquals(4, ThreadLocalWatch.pop(stack)); Assert.assertEquals(1, ThreadLocalWatch.pop(stack)); Assert.assertEquals(0, ThreadLocalWatch.pop(stack)); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/matcher/RegexMatcherTest.java
core/src/test/java/com/taobao/arthas/core/util/matcher/RegexMatcherTest.java
package com.taobao.arthas.core.util.matcher; import org.junit.Assert; import org.junit.Test; /** * @author earayu */ public class RegexMatcherTest { @Test public void testMatchingWithNullInputs(){ Assert.assertFalse(new RegexMatcher(null).matching(null)); Assert.assertFalse(new RegexMatcher(null).matching("foobar")); Assert.assertFalse(new RegexMatcher("foobar").matching(null)); Assert.assertTrue(new RegexMatcher("foobar").matching("foobar")); } /** * test regux with . | * + ? \s \S \w \W and so on... */ @Test public void testMatchingWithRegularGrammar(){ Assert.assertTrue(new RegexMatcher("foo?").matching("fo")); Assert.assertTrue(new RegexMatcher("foo?").matching("foo")); Assert.assertTrue(new RegexMatcher("foo.").matching("fooo")); Assert.assertTrue(new RegexMatcher("foo*").matching("fooooo")); Assert.assertTrue(new RegexMatcher("foo.*").matching("foobarbarbar")); Assert.assertFalse(new RegexMatcher("foo+").matching("fo")); Assert.assertTrue(new RegexMatcher("foo+").matching("fooooo")); Assert.assertTrue(new RegexMatcher("foo\\s").matching("foo ")); Assert.assertFalse(new RegexMatcher("foo\\S").matching("foo ")); Assert.assertTrue(new RegexMatcher("foo\\w").matching("fooo")); Assert.assertTrue(new RegexMatcher("foo\\W").matching("foo ")); Assert.assertFalse(new RegexMatcher("foo\\W").matching("fooo")); Assert.assertTrue(new RegexMatcher("foo[1234]").matching("foo1")); Assert.assertFalse(new RegexMatcher("foo[1234]").matching("foo5")); Assert.assertTrue(new RegexMatcher("foo\\\\").matching("foo\\")); Assert.assertTrue(new RegexMatcher("foo\\d").matching("foo5")); Assert.assertTrue(new RegexMatcher("fo{1,3}").matching("fo")); Assert.assertFalse(new RegexMatcher("fo{1,3}").matching("foooo")); } @Test public void testMatchingComplexRegex(){ String ipAddressPattern = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)"; Assert.assertTrue(new RegexMatcher(ipAddressPattern).matching("1.1.1.1")); Assert.assertFalse(new RegexMatcher(ipAddressPattern).matching("255.256.255.0")); Assert.assertFalse(new RegexMatcher(ipAddressPattern).matching("1.1.1")); Assert.assertTrue(new RegexMatcher("^foobar$").matching("foobar")); Assert.assertFalse(new RegexMatcher("^foobar$").matching("\nfoobar")); Assert.assertFalse(new RegexMatcher("^foobar$").matching("foobar\n")); String emailAddressPattern = "[a-z\\d]+(\\.[a-z\\d]+)*@([\\da-z](-[\\da-z])?)+(\\.{1,2}[a-z]+)+"; Assert.assertTrue(new RegexMatcher(emailAddressPattern).matching("foo@bar.com")); Assert.assertFalse(new RegexMatcher(emailAddressPattern).matching("asdfghjkl")); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/matcher/FalseMatcherTest.java
core/src/test/java/com/taobao/arthas/core/util/matcher/FalseMatcherTest.java
package com.taobao.arthas.core.util.matcher; import org.junit.Assert; import org.junit.Test; /** * @author earayu */ public class FalseMatcherTest { @Test public void testMatching(){ Assert.assertFalse(new FalseMatcher<String>().matching(null)); Assert.assertFalse(new FalseMatcher<Integer>().matching(1)); Assert.assertFalse(new FalseMatcher<String>().matching("")); Assert.assertFalse(new FalseMatcher<String>().matching("foobar")); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/matcher/EqualsMatcherTest.java
core/src/test/java/com/taobao/arthas/core/util/matcher/EqualsMatcherTest.java
package com.taobao.arthas.core.util.matcher; import org.junit.Assert; import org.junit.Test; /** * @author earayu */ public class EqualsMatcherTest { @Test public void testMatching(){ Assert.assertTrue(new EqualsMatcher<String>(null).matching(null)); Assert.assertTrue(new EqualsMatcher<String>("").matching("")); Assert.assertTrue(new EqualsMatcher<String>("foobar").matching("foobar")); Assert.assertFalse(new EqualsMatcher<String>("").matching(null)); Assert.assertFalse(new EqualsMatcher<String>("abc").matching("def")); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/matcher/WildcardMatcherTest.java
core/src/test/java/com/taobao/arthas/core/util/matcher/WildcardMatcherTest.java
package com.taobao.arthas.core.util.matcher; import org.junit.Assert; import org.junit.Test; /** * @author earayu */ public class WildcardMatcherTest { @Test public void testMatching(){ Assert.assertFalse(new WildcardMatcher(null).matching(null)); Assert.assertFalse(new WildcardMatcher(null).matching("foo")); Assert.assertFalse(new WildcardMatcher("foo").matching(null)); Assert.assertTrue(new WildcardMatcher("foo").matching("foo")); Assert.assertFalse(new WildcardMatcher("foo").matching("bar")); Assert.assertTrue(new WildcardMatcher("foo*").matching("foo")); Assert.assertTrue(new WildcardMatcher("foo*").matching("fooooooobar")); Assert.assertTrue(new WildcardMatcher("f*r").matching("fooooooobar")); Assert.assertFalse(new WildcardMatcher("foo*").matching("fo")); Assert.assertFalse(new WildcardMatcher("foo*").matching("bar")); Assert.assertFalse(new WildcardMatcher("foo?").matching("foo")); Assert.assertTrue(new WildcardMatcher("foo?").matching("foob")); Assert.assertTrue(new WildcardMatcher("foo\\*").matching("foo*")); Assert.assertFalse(new WildcardMatcher("foo\\*").matching("foooooo")); Assert.assertTrue(new WildcardMatcher("foo\\?").matching("foo?")); Assert.assertFalse(new WildcardMatcher("foo\\?").matching("foob")); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/util/matcher/TrueMatcherTest.java
core/src/test/java/com/taobao/arthas/core/util/matcher/TrueMatcherTest.java
package com.taobao.arthas.core.util.matcher; import org.junit.Assert; import org.junit.Test; /** * @author earayu */ public class TrueMatcherTest { @Test public void testMatching(){ Assert.assertTrue(new TrueMatcher<String>().matching(null)); Assert.assertTrue(new TrueMatcher<Integer>().matching(1)); Assert.assertTrue(new TrueMatcher<String>().matching("")); Assert.assertTrue(new TrueMatcher<String>().matching("foobar")); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/env/ArthasEnvironmentTest.java
core/src/test/java/com/taobao/arthas/core/env/ArthasEnvironmentTest.java
package com.taobao.arthas.core.env; import java.util.Properties; import org.assertj.core.api.Assertions; import org.junit.Test; /** * * @author hengyunabc 2019-12-27 * */ public class ArthasEnvironmentTest { @Test public void test() { ArthasEnvironment arthasEnvironment = new ArthasEnvironment(); Assertions.assertThat(arthasEnvironment.resolvePlaceholders("hello, ${java.version}")) .isEqualTo("hello, " + System.getProperty("java.version")); Assertions.assertThat(arthasEnvironment.resolvePlaceholders("hello, ${xxxxxxxxxxxxxxx}")) .isEqualTo("hello, ${xxxxxxxxxxxxxxx}"); System.setProperty("xxxxxxxxxxxxxxx", "vvv"); Assertions.assertThat(arthasEnvironment.resolvePlaceholders("hello, ${xxxxxxxxxxxxxxx}")) .isEqualTo("hello, vvv"); System.clearProperty("xxxxxxxxxxxxxxx"); } @Test public void test_properties() { ArthasEnvironment arthasEnvironment = new ArthasEnvironment(); Properties properties1 = new Properties(); Properties properties2 = new Properties(); arthasEnvironment.addLast(new PropertiesPropertySource("test1", properties1)); arthasEnvironment.addLast(new PropertiesPropertySource("test2", properties2)); properties2.put("test.key", "2222"); Assertions.assertThat(arthasEnvironment.resolvePlaceholders("hello, ${test.key}")).isEqualTo("hello, 2222"); properties1.put("java.version", "test"); properties1.put("test.key", "test"); Assertions.assertThat(arthasEnvironment.resolvePlaceholders("hello, ${java.version}")) .isEqualTo("hello, " + System.getProperty("java.version")); Assertions.assertThat(arthasEnvironment.resolvePlaceholders("hello, ${test.key}")).isEqualTo("hello, test"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/advisor/SpyImplTest.java
core/src/test/java/com/taobao/arthas/core/advisor/SpyImplTest.java
package com.taobao.arthas.core.advisor; import org.assertj.core.api.Assertions; import org.junit.Test; import com.taobao.arthas.core.util.StringUtils; /** * * @author hengyunabc 2021-07-14 * */ public class SpyImplTest { @Test public void testSplitMethodInfo() throws Throwable { Assertions.assertThat(StringUtils.splitMethodInfo("a|b")).containsExactly("a", "b"); Assertions.assertThat(StringUtils.splitMethodInfo("xxxxxxxxxx|fffffffffff")).containsExactly("xxxxxxxxxx", "fffffffffff"); Assertions.assertThat(StringUtils.splitMethodInfo("print|(ILjava/util/List;)V")).containsExactly("print", "(ILjava/util/List;)V"); } @Test public void testSplitInvokeInfo() throws Throwable { Assertions.assertThat(StringUtils.splitInvokeInfo("demo/MathGame|primeFactors|(I)Ljava/util/List;|24")) .containsExactly("demo/MathGame", "primeFactors", "(I)Ljava/util/List;", "24"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/advisor/EnhancerTest.java
core/src/test/java/com/taobao/arthas/core/advisor/EnhancerTest.java
package com.taobao.arthas.core.advisor; import java.arthas.SpyAPI; import java.lang.instrument.Instrumentation; import org.assertj.core.api.Assertions; import org.junit.Test; import org.mockito.Mockito; import com.alibaba.bytekit.utils.AsmUtils; import com.alibaba.bytekit.utils.Decompiler; import com.alibaba.deps.org.objectweb.asm.Type; import com.alibaba.deps.org.objectweb.asm.tree.ClassNode; import com.alibaba.deps.org.objectweb.asm.tree.MethodNode; import com.taobao.arthas.core.bytecode.TestHelper; import com.taobao.arthas.core.server.ArthasBootstrap; import com.taobao.arthas.core.util.matcher.EqualsMatcher; import demo.MathGame; import net.bytebuddy.agent.ByteBuddyAgent; /** * * @author hengyunabc 2020-05-19 * */ public class EnhancerTest { @Test public void test() throws Throwable { Instrumentation instrumentation = ByteBuddyAgent.install(); TestHelper.appendSpyJar(instrumentation); ArthasBootstrap.getInstance(instrumentation, "ip=127.0.0.1"); AdviceListener listener = Mockito.mock(AdviceListener.class); EqualsMatcher<String> methodNameMatcher = new EqualsMatcher<String>("print"); EqualsMatcher<String> classNameMatcher = new EqualsMatcher<String>(MathGame.class.getName()); Enhancer enhancer = new Enhancer(listener, true, false, classNameMatcher, null, methodNameMatcher); ClassLoader inClassLoader = MathGame.class.getClassLoader(); String className = MathGame.class.getName(); Class<?> classBeingRedefined = MathGame.class; ClassNode classNode = AsmUtils.loadClass(MathGame.class); byte[] classfileBuffer = AsmUtils.toBytes(classNode); byte[] result = enhancer.transform(inClassLoader, className, classBeingRedefined, null, classfileBuffer); ClassNode resultClassNode1 = AsmUtils.toClassNode(result); // FileUtils.writeByteArrayToFile(new File("/tmp/MathGame1.class"), result); result = enhancer.transform(inClassLoader, className, classBeingRedefined, null, result); ClassNode resultClassNode2 = AsmUtils.toClassNode(result); // FileUtils.writeByteArrayToFile(new File("/tmp/MathGame2.class"), result); MethodNode resultMethodNode1 = AsmUtils.findMethods(resultClassNode1.methods, "print").get(0); MethodNode resultMethodNode2 = AsmUtils.findMethods(resultClassNode2.methods, "print").get(0); Assertions .assertThat(AsmUtils .findMethodInsnNode(resultMethodNode1, Type.getInternalName(SpyAPI.class), "atEnter").size()) .isEqualTo(AsmUtils.findMethodInsnNode(resultMethodNode2, Type.getInternalName(SpyAPI.class), "atEnter") .size()); Assertions.assertThat(AsmUtils .findMethodInsnNode(resultMethodNode1, Type.getInternalName(SpyAPI.class), "atExceptionExit").size()) .isEqualTo(AsmUtils .findMethodInsnNode(resultMethodNode2, Type.getInternalName(SpyAPI.class), "atExceptionExit") .size()); Assertions.assertThat(AsmUtils .findMethodInsnNode(resultMethodNode1, Type.getInternalName(SpyAPI.class), "atBeforeInvoke").size()) .isEqualTo(AsmUtils .findMethodInsnNode(resultMethodNode2, Type.getInternalName(SpyAPI.class), "atBeforeInvoke") .size()); Assertions.assertThat(AsmUtils .findMethodInsnNode(resultMethodNode1, Type.getInternalName(SpyAPI.class), "atInvokeException").size()) .isEqualTo(AsmUtils .findMethodInsnNode(resultMethodNode2, Type.getInternalName(SpyAPI.class), "atInvokeException") .size()); String string = Decompiler.decompile(result); System.err.println(string); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/command/klass100/ClassLoaderCommandUrlClassesTest.java
core/src/test/java/com/taobao/arthas/core/command/klass100/ClassLoaderCommandUrlClassesTest.java
package com.taobao.arthas.core.command.klass100; import org.junit.Assert; import org.junit.Test; public class ClassLoaderCommandUrlClassesTest { @Test public void testGuessJarNameForNestedJarUrl() { String url = "jar:file:/app.jar!/BOOT-INF/lib/spring-core-5.3.0.jar!/"; Assert.assertEquals("spring-core-5.3.0.jar", ClassLoaderCommand.guessJarName(url)); } @Test public void testGuessJarNameForFileJarUrl() { String url = "file:/private/tmp/math-game.jar"; Assert.assertEquals("math-game.jar", ClassLoaderCommand.guessJarName(url)); } @Test public void testGuessJarNameForDirectoryUrl() { String url = "file:/private/tmp/classes/"; Assert.assertEquals("classes", ClassLoaderCommand.guessJarName(url)); } @Test public void testContainsIgnoreCase() { Assert.assertTrue(ClassLoaderCommand.containsIgnoreCase("Spring-Core-5.3.0.jar", "spring-core")); Assert.assertTrue(ClassLoaderCommand.containsIgnoreCase("org.springframework.web", "SpringFramework")); Assert.assertFalse(ClassLoaderCommand.containsIgnoreCase("demo.MathGame", "org.springframework")); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/command/basic1000/GrepCommandTest.java
core/src/test/java/com/taobao/arthas/core/command/basic1000/GrepCommandTest.java
package com.taobao.arthas.core.command.basic1000; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.taobao.middleware.cli.CLI; import com.taobao.middleware.cli.CommandLine; import com.taobao.middleware.cli.annotations.CLIConfigurator; /** * * @author hengyunabc 2019-10-31 * */ public class GrepCommandTest { private static CLI cli = null; @Before public void before() { cli = CLIConfigurator.define(GrepCommand.class); } @Test public void test() { List<String> args = Arrays.asList("-v", "ppp"); GrepCommand grepCommand = new GrepCommand(); CommandLine commandLine = cli.parse(args, true); try { CLIConfigurator.inject(commandLine, grepCommand); } catch (Throwable e) { throw new RuntimeException(e); } Assert.assertTrue(grepCommand.isInvertMatch()); } @Test public void test2() { List<String> args = Arrays.asList("--before-context=6", "ppp"); GrepCommand grepCommand = new GrepCommand(); CommandLine commandLine = cli.parse(args, true); try { CLIConfigurator.inject(commandLine, grepCommand); } catch (Throwable e) { throw new RuntimeException(e); } Assert.assertEquals(6, grepCommand.getBeforeLines()); } @Test public void test3() { List<String> args = Arrays.asList("--trim-end=false", "ppp"); GrepCommand grepCommand = new GrepCommand(); CommandLine commandLine = cli.parse(args, true); try { CLIConfigurator.inject(commandLine, grepCommand); } catch (Throwable e) { throw new RuntimeException(e); } Assert.assertFalse(grepCommand.isTrimEnd()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/command/express/OgnlTest.java
core/src/test/java/com/taobao/arthas/core/command/express/OgnlTest.java
package com.taobao.arthas.core.command.express; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.taobao.arthas.core.advisor.Advice; import ognl.OgnlException; import static org.junit.jupiter.api.Assertions.assertTrue; /** * https://github.com/alibaba/arthas/issues/2954 */ public class OgnlTest { private Express express; @BeforeEach public void setUp() throws OgnlException, ExpressException { FlowContext context = new FlowContext(); Object[] params = new Object[4]; params[0] = context; Advice advice = Advice.newForAfterReturning(null, getClass(), null, null, params, null); express = ExpressFactory.unpooledExpress(null).bind(advice).bind("cost", 123); } @Test public void testStringEquals() throws OgnlException, ExpressException { String conditionExpress = "\"aaa\".equals(params[0].flowAttribute.getBxApp())"; boolean result = express.is(conditionExpress); assertTrue(result); } @Test public void testObjectEquals() throws OgnlException, ExpressException { String conditionExpress = "params[0].flowAttribute.getBxApp().equals(\"aaa\")"; boolean result = express.is(conditionExpress); assertTrue(result); } @Test public void testEqualSign() throws OgnlException, ExpressException { String conditionExpress = "\"aaa\" == params[0].flowAttribute.getBxApp()"; boolean result = express.is(conditionExpress); assertTrue(result); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/command/express/FlowContext.java
core/src/test/java/com/taobao/arthas/core/command/express/FlowContext.java
package com.taobao.arthas.core.command.express; public class FlowContext { private FlowAttribute flowAttribute = new FlowAttribute(); public FlowAttribute getFlowAttribute() { return this.flowAttribute ; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/command/express/OgnlExpressTest.java
core/src/test/java/com/taobao/arthas/core/command/express/OgnlExpressTest.java
package com.taobao.arthas.core.command.express; import org.junit.Assert; import org.junit.Test; public class OgnlExpressTest { @Test public void testValidOgnlExpr1() throws ExpressException { Express unpooledExpress = ExpressFactory.unpooledExpress(OgnlExpressTest.class.getClassLoader()); Assert.assertEquals(unpooledExpress.get("\"test\".length() % 2 == 0 ? \"even length\" : \"odd length\""), "even length"); } @Test public void testValidOgnlExpr2() throws ExpressException { System.setProperty("ognl.chain.short-circuit", String.valueOf(false)); Express unpooledExpress = ExpressFactory.unpooledExpress(OgnlExpressTest.class.getClassLoader()); Assert.assertEquals(unpooledExpress.get("4 in {1, 2, 3, 4}"), true); Assert.assertEquals(unpooledExpress.get("{1, 2, 3, 4}.{^ #this % 2 == 0}[$]"), 2); Assert.assertEquals(unpooledExpress.get("{1, 2, 3, 4}.{? #this % 2 == 0}[$]"), 4); } @Test public void testValidOgnlExpr3() throws ExpressException { Express unpooledExpress = ExpressFactory.unpooledExpress(OgnlExpressTest.class.getClassLoader()); Assert.assertEquals(unpooledExpress.get("#factorial = :[#this <= 1 ? 1 : #this * #factorial(#this - 1)], #factorial(5)"), 120); } @Test public void testValidOgnlExpr4() throws ExpressException { Express unpooledExpress = ExpressFactory.unpooledExpress(OgnlExpressTest.class.getClassLoader()); System.setProperty("arthas.test1", "arthas"); System.setProperty("arthas.ognl.test2", "test"); Assert.assertEquals(unpooledExpress.get("#value1=@System@getProperty(\"arthas.test1\")," + "#value2=@System@getProperty(\"arthas.ognl.test2\"), {#value1, #value2}").toString(), "[arthas, test]"); System.clearProperty("arthas.test1"); System.clearProperty("arthas.ognl.test2"); } @Test public void testInvalidOgnlExpr() { try { Express unpooledExpress = ExpressFactory.unpooledExpress(OgnlExpressTest.class.getClassLoader()); System.out.println(unpooledExpress.get("#value1=@System.getProperty(\"java.home\")," + "#value2=@System@getProperty(\"java.runtime.name\"), {#value1, #value2}").toString()); } catch (Exception e){ Assert.assertTrue(e.getCause() instanceof ognl.ExpressionSyntaxException); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/command/express/FlowAttribute.java
core/src/test/java/com/taobao/arthas/core/command/express/FlowAttribute.java
package com.taobao.arthas.core.command.express; public class FlowAttribute { private String bxApp = "aaa"; public String getBxApp() { return this.bxApp ; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/bytecode/TestHelper.java
core/src/test/java/com/taobao/arthas/core/bytecode/TestHelper.java
package com.taobao.arthas.core.bytecode; import java.io.File; import java.io.IOException; import java.lang.instrument.Instrumentation; import java.util.ArrayList; import java.util.List; import java.util.jar.JarFile; import org.zeroturnaround.zip.ZipUtil; import com.alibaba.deps.org.objectweb.asm.tree.ClassNode; import com.alibaba.deps.org.objectweb.asm.tree.MethodNode; import com.alibaba.bytekit.asm.MethodProcessor; import com.alibaba.bytekit.asm.interceptor.InterceptorProcessor; import com.alibaba.bytekit.asm.interceptor.parser.DefaultInterceptorClassParser; import com.alibaba.bytekit.utils.AgentUtils; import com.alibaba.bytekit.utils.AsmUtils; import com.alibaba.bytekit.utils.MatchUtils; import com.alibaba.bytekit.utils.VerifyUtils; /** * * @author hengyunabc 2020-05-19 * */ public class TestHelper { private Class<?> interceptorClass; private boolean redefine; private String methodMatcher = "*"; private boolean asmVerity = true; public static TestHelper builder() { return new TestHelper(); } public TestHelper interceptorClass(Class<?> interceptorClass) { this.interceptorClass = interceptorClass; return this; } public TestHelper redefine(boolean redefine) { this.redefine = redefine; return this; } public TestHelper methodMatcher(String methodMatcher) { this.methodMatcher = methodMatcher; return this; } public byte[] process(Class<?> transform) throws Exception { DefaultInterceptorClassParser defaultInterceptorClassParser = new DefaultInterceptorClassParser(); List<InterceptorProcessor> interceptorProcessors = defaultInterceptorClassParser.parse(interceptorClass); ClassNode classNode = AsmUtils.loadClass(transform); List<MethodNode> matchedMethods = new ArrayList<MethodNode>(); for (MethodNode methodNode : classNode.methods) { if (MatchUtils.wildcardMatch(methodNode.name, methodMatcher)) { matchedMethods.add(methodNode); } } for (MethodNode methodNode : matchedMethods) { MethodProcessor methodProcessor = new MethodProcessor(classNode, methodNode); for (InterceptorProcessor interceptor : interceptorProcessors) { interceptor.process(methodProcessor); } } byte[] bytes = AsmUtils.toBytes(classNode); if (asmVerity) { VerifyUtils.asmVerify(bytes); } if (redefine) { AgentUtils.redefine(transform, bytes); } return bytes; } public static void appendSpyJar(Instrumentation instrumentation) throws IOException { // find spy target/classes directory String file = TestHelper.class.getProtectionDomain().getCodeSource().getLocation().getFile(); File spyClassDir = new File(file, "../../../spy/target/classes").getAbsoluteFile(); File destJarFile = new File(file, "../../../spy/target/test-spy.jar").getAbsoluteFile(); ZipUtil.pack(spyClassDir, destJarFile); instrumentation.appendToBootstrapClassLoaderSearch(new JarFile(destJarFile)); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/view/ObjectViewTest.java
core/src/test/java/com/taobao/arthas/core/view/ObjectViewTest.java
package com.taobao.arthas.core.view; import com.taobao.arthas.core.GlobalOptions; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; /** * @author ralf0131 2018-07-10 10:55. */ public class ObjectViewTest { @Test public void testNull() { ObjectView objectView = new ObjectView(null, 3); Assert.assertEquals("null", objectView.draw()); } @Test public void testInteger() { ObjectView objectView = new ObjectView(new Integer(1), 3); Assert.assertEquals("@Integer[1]", objectView.draw()); } @Test public void testChar() { ObjectView objectView = new ObjectView(new Character('中'), 3); Assert.assertEquals("@Character[中]", objectView.draw()); } @Test public void testString() { ObjectView objectView = new ObjectView("hello\nworld!", 3); Assert.assertEquals("@String[hello\\nworld!]", objectView.draw()); } @Test public void testList() { List<String> data = new ArrayList<String>(); data.add("aaa"); data.add("bbb"); ObjectView objectView = new ObjectView(data, 3); String expected = "@ArrayList[\n" + " @String[aaa],\n" + " @String[bbb],\n" + "]"; Assert.assertEquals(expected, objectView.draw()); } @Test public void testMap() { Map<String, String> data = new LinkedHashMap<String, String>(); data.put("key1", "value1"); data.put("key2", "value2"); ObjectView objectView = new ObjectView(data, 3); String expected = "@LinkedHashMap[\n" + " @String[key1]:@String[value1],\n" + " @String[key2]:@String[value2],\n" + "]"; Assert.assertEquals(expected, objectView.draw()); } @Test public void testIntArray() { int[] data = {1,3,4,5}; ObjectView objectView = new ObjectView(data, 3); String expected = "@int[][\n" + " @Integer[1],\n" + " @Integer[3],\n" + " @Integer[4],\n" + " @Integer[5],\n" + "]"; Assert.assertEquals(expected, objectView.draw()); } @Test public void testLongArray() { long[] data = {1L,3L,4L,5L}; ObjectView objectView = new ObjectView(data, 3); String expected = "@long[][\n" + " @Long[1],\n" + " @Long[3],\n" + " @Long[4],\n" + " @Long[5],\n" + "]"; Assert.assertEquals(expected, objectView.draw()); } @Test public void testShortArray() { short[] data = {1,3,4,5}; ObjectView objectView = new ObjectView(data, 3); String expected = "@short[][\n" + " @Short[1],\n" + " @Short[3],\n" + " @Short[4],\n" + " @Short[5],\n" + "]"; Assert.assertEquals(expected, objectView.draw()); } @Test public void testFloatArray() { float[] data = {1.0f, 3.0f, 4.2f, 5.3f}; ObjectView objectView = new ObjectView(data, 3); String expected = "@float[][\n" + " @Float[1.0],\n" + " @Float[3.0],\n" + " @Float[4.2],\n" + " @Float[5.3],\n" + "]"; Assert.assertEquals(expected, objectView.draw()); } @Test public void testDoubleArray() { double[] data = {1.0d, 3.0d, 4.2d, 5.3d}; ObjectView objectView = new ObjectView(data, 3); String expected = "@double[][\n" + " @Double[1.0],\n" + " @Double[3.0],\n" + " @Double[4.2],\n" + " @Double[5.3],\n" + "]"; Assert.assertEquals(expected, objectView.draw()); } @Test public void testBooleanArray() { boolean[] data = {true, false, true, true}; ObjectView objectView = new ObjectView(data, 3); String expected = "@boolean[][\n" + " @Boolean[true],\n" + " @Boolean[false],\n" + " @Boolean[true],\n" + " @Boolean[true],\n" + "]"; Assert.assertEquals(expected, objectView.draw()); } @Test public void testCharArray() { char[] data = {'a', 'b', 'c', 'd'}; ObjectView objectView = new ObjectView(data, 3); String expected = "@char[][\n" + " @Character[a],\n" + " @Character[b],\n" + " @Character[c],\n" + " @Character[d],\n" + "]"; Assert.assertEquals(expected, objectView.draw()); } @Test public void testByteArray() { byte[] data = {'a', 'b', 'c', 'd'}; ObjectView objectView = new ObjectView(data, 3); String expected = "@byte[][\n" + " @Byte[97],\n" + " @Byte[98],\n" + " @Byte[99],\n" + " @Byte[100],\n" + "]"; Assert.assertEquals(expected, objectView.draw()); } @Test public void testObjectArray() { String[] data = {"111", "222", "333", "444"}; ObjectView objectView = new ObjectView(data, 3); String expected = "@String[][\n" + " @String[111],\n" + " @String[222],\n" + " @String[333],\n" + " @String[444],\n" + "]"; Assert.assertEquals(expected, objectView.draw()); } @Test public void testThrowable() { Exception t = new Exception("test"); ObjectView objectView = new ObjectView(t, 3); Assert.assertTrue(objectView.draw().startsWith("java.lang.Exception: test")); } @Test public void testEnum() { EnumDemo t = EnumDemo.DEMO; ObjectView objectView = new ObjectView(t, 3); Assert.assertEquals("@EnumDemo[DEMO]", objectView.draw()); } @Test public void testEnumList() { EnumDemo t = EnumDemo.DEMO; ObjectView objectView = new ObjectView(new Object[] {t}, 3); String expected = "@Object[][\n" + " @EnumDemo[DEMO],\n" + "]"; Assert.assertEquals(expected, objectView.draw()); } @Test public void testJsonFormatDoNotCreateNewInstance() { boolean old = GlobalOptions.isUsingJson; try { JsonFormatSingleton singleton = JsonFormatSingleton.getInstance(); GlobalOptions.isUsingJson = true; ObjectView objectView = new ObjectView(new Object[] { singleton }, 3); String output = objectView.draw(); Assert.assertFalse(output.startsWith("ERROR DATA!!!")); Assert.assertEquals(1, JsonFormatSingleton.constructorCalls); } finally { GlobalOptions.isUsingJson = old; } } @Test public void testDate() { Date d = new Date(1531204354961L - TimeZone.getDefault().getRawOffset() + TimeZone.getTimeZone("GMT+8").getRawOffset()); ObjectView objectView = new ObjectView(d, 3); String expected = "@Date[2018-07-10 14:32:34,961]"; Assert.assertEquals(expected, objectView.draw()); } @Test public void testNestedClass() { ObjectView objectView = new ObjectView(new NestedClass(100), 3); String expected = "@NestedClass[\n" + " code=@Integer[100],\n" + " c1=@NestedClass[\n" + " code=@Integer[1],\n" + " c1=@NestedClass[\n" + " code=@Integer[1],\n" + " c1=@NestedClass[com.taobao.arthas.core.view.ObjectViewTest$NestedClass@ffffffff],\n" + " c2=@NestedClass[com.taobao.arthas.core.view.ObjectViewTest$NestedClass@ffffffff],\n" + " ],\n" + " c2=@NestedClass[\n" + " code=@Integer[2],\n" + " c1=@NestedClass[com.taobao.arthas.core.view.ObjectViewTest$NestedClass@ffffffff],\n" + " c2=@NestedClass[com.taobao.arthas.core.view.ObjectViewTest$NestedClass@ffffffff],\n" + " ],\n" + " ],\n" + " c2=@NestedClass[\n" + " code=@Integer[2],\n" + " c1=@NestedClass[\n" + " code=@Integer[1],\n" + " c1=@NestedClass[com.taobao.arthas.core.view.ObjectViewTest$NestedClass@ffffffff],\n" + " c2=@NestedClass[com.taobao.arthas.core.view.ObjectViewTest$NestedClass@ffffffff],\n" + " ],\n" + " c2=@NestedClass[\n" + " code=@Integer[2],\n" + " c1=@NestedClass[com.taobao.arthas.core.view.ObjectViewTest$NestedClass@ffffffff],\n" + " c2=@NestedClass[com.taobao.arthas.core.view.ObjectViewTest$NestedClass@ffffffff],\n" + " ],\n" + " ],\n" + "]"; Assert.assertEquals(expected, replaceHashCode(objectView.draw())); } @Test public void testObjectTooLarge() { ObjectView objectView = new ObjectView(new NestedClass(100), 3, 100); String expected = "@NestedClass[\n" + " code=@Integer[100],\n" + " c1=@NestedClass[\n" + " code=@Integer[1],\n" + " c1=...\n" + "... Object size exceeds size limit: 100, try to specify -M size_limit in your command, check the help command for more."; Assert.assertEquals(expected, objectView.draw()); } private String replaceHashCode(String input) { return input.replaceAll("@[0-9a-f]+", "@ffffffff"); } private static class NestedClass { private int code; private static NestedClass c1 = get(1); private static NestedClass c2 = get(2); public NestedClass(int code) { this.code = code; } private static NestedClass get(int code) { return new NestedClass(code); } } /** * 显示基类属性值 */ @Test public void testObjectViewBaseFieldValue() { SonBean sonBean = new SonBean(); sonBean.setI(10); sonBean.setJ("test"); ObjectView objectView = new ObjectView(sonBean, 3, 100); Assert.assertTrue(objectView.draw().contains("i=@Integer[10]")); } private class BaseBean { private int i; public int getI() { return i; } public void setI(int i) { this.i = i; } } private class SonBean extends BaseBean { private String j; public String getJ() { return j; } public void setJ(String j) { this.j = j; } } public enum EnumDemo { DEMO; } public static class JsonFormatSingleton { private static final JsonFormatSingleton INSTANCE; private static volatile int constructorCalls = 0; static { INSTANCE = new JsonFormatSingleton(); } private JsonFormatSingleton() { constructorCalls++; if (constructorCalls > 1) { throw new IllegalStateException("JsonFormatSingleton is created!"); } } public static JsonFormatSingleton getInstance() { return INSTANCE; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/security/SecurityAuthenticatorImplTest.java
core/src/test/java/com/taobao/arthas/core/security/SecurityAuthenticatorImplTest.java
package com.taobao.arthas.core.security; import java.security.Principal; import javax.security.auth.Subject; import javax.security.auth.login.LoginException; import org.assertj.core.api.Assertions; import org.junit.Test; /** * * @author hengyunabc 2021-03-04 * */ public class SecurityAuthenticatorImplTest { @Test public void test1() throws LoginException { String username = "test"; String password = "ppp"; SecurityAuthenticatorImpl auth = new SecurityAuthenticatorImpl(username, password); Assertions.assertThat(auth.needLogin()).isTrue(); Principal principal = new BasicPrincipal(username, password); Subject subject = auth.login(principal); Assertions.assertThat(subject).isNotNull(); } @Test public void test2() { String username = "test"; String password = null; SecurityAuthenticatorImpl auth = new SecurityAuthenticatorImpl(username, password); Assertions.assertThat(auth.needLogin()).isTrue(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/server/ArthasBootstrapTest.java
core/src/test/java/com/taobao/arthas/core/server/ArthasBootstrapTest.java
package com.taobao.arthas.core.server; import static org.assertj.core.api.Assertions.assertThat; import java.lang.instrument.Instrumentation; import java.lang.reflect.Field; import org.jboss.modules.ModuleClassLoader; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import com.alibaba.bytekit.utils.ReflectionUtils; import com.taobao.arthas.common.JavaVersionUtils; import com.taobao.arthas.core.bytecode.TestHelper; import com.taobao.arthas.core.config.Configure; import com.taobao.arthas.core.env.ArthasEnvironment; import net.bytebuddy.agent.ByteBuddyAgent; /** * * @author hengyunabc 2020-12-02 * */ public class ArthasBootstrapTest { @Before public void beforeMethod() { // jboss modules need jdk8 org.junit.Assume.assumeTrue(JavaVersionUtils.isGreaterThanJava7()); } @Test public void test() throws Exception { Instrumentation instrumentation = ByteBuddyAgent.install(); TestHelper.appendSpyJar(instrumentation); ArthasBootstrap arthasBootstrap = Mockito.mock(ArthasBootstrap.class); Mockito.doCallRealMethod().when(arthasBootstrap).enhanceClassLoader(); Configure configure = Mockito.mock(Configure.class); Mockito.when(configure.getEnhanceLoaders()) .thenReturn("java.lang.ClassLoader,org.jboss.modules.ConcurrentClassLoader"); Field configureField = ArthasBootstrap.class.getDeclaredField("configure"); configureField.setAccessible(true); ReflectionUtils.setField(configureField, arthasBootstrap, configure); Field instrumentationField = ArthasBootstrap.class.getDeclaredField("instrumentation"); instrumentationField.setAccessible(true); ReflectionUtils.setField(instrumentationField, arthasBootstrap, instrumentation); org.jboss.modules.ModuleClassLoader moduleClassLoader = Mockito.mock(ModuleClassLoader.class); boolean flag = false; try { moduleClassLoader.loadClass("java.arthas.SpyAPI"); } catch (Exception e) { flag = true; } assertThat(flag).isTrue(); arthasBootstrap.enhanceClassLoader(); Class<?> loadClass = moduleClassLoader.loadClass("java.arthas.SpyAPI"); System.err.println(loadClass); } @Test public void testConfigLocationNull() throws Exception { ArthasEnvironment arthasEnvironment = new ArthasEnvironment(); String location = ArthasBootstrap.reslove(arthasEnvironment, ArthasBootstrap.CONFIG_LOCATION_PROPERTY, null); assertThat(location).isEqualTo(null); } @Test public void testConfigLocation() throws Exception { ArthasEnvironment arthasEnvironment = new ArthasEnvironment(); System.setProperty("hhhh", "fff"); System.setProperty(ArthasBootstrap.CONFIG_LOCATION_PROPERTY, "test${hhhh}"); String location = ArthasBootstrap.reslove(arthasEnvironment, ArthasBootstrap.CONFIG_LOCATION_PROPERTY, null); System.clearProperty("hhhh"); System.clearProperty(ArthasBootstrap.CONFIG_LOCATION_PROPERTY); assertThat(location).isEqualTo("test" + "fff"); } @Test public void testConfigNameDefault() throws Exception { ArthasEnvironment arthasEnvironment = new ArthasEnvironment(); String configName = ArthasBootstrap.reslove(arthasEnvironment, ArthasBootstrap.CONFIG_NAME_PROPERTY, "arthas"); assertThat(configName).isEqualTo("arthas"); } @Test public void testConfigName() throws Exception { ArthasEnvironment arthasEnvironment = new ArthasEnvironment(); System.setProperty(ArthasBootstrap.CONFIG_NAME_PROPERTY, "testName"); String configName = ArthasBootstrap.reslove(arthasEnvironment, ArthasBootstrap.CONFIG_NAME_PROPERTY, "arthas"); System.clearProperty(ArthasBootstrap.CONFIG_NAME_PROPERTY); assertThat(configName).isEqualTo("testName"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/config/ErrorProperties.java
core/src/test/java/com/taobao/arthas/core/config/ErrorProperties.java
package com.taobao.arthas.core.config; public class ErrorProperties { /** * Path of the error controller. */ // @Value("${error.path:/error}") private String path = "/error"; /** * When to include a "stacktrace" attribute. */ private IncludeStacktrace includeStacktrace = IncludeStacktrace.NEVER; public String getPath() { return this.path; } public void setPath(String path) { this.path = path; } public IncludeStacktrace getIncludeStacktrace() { return this.includeStacktrace; } public void setIncludeStacktrace(IncludeStacktrace includeStacktrace) { this.includeStacktrace = includeStacktrace; } @Override public String toString() { return "ErrorProperties [path=" + path + ", includeStacktrace=" + includeStacktrace + "]"; } /** * Include Stacktrace attribute options. */ public enum IncludeStacktrace { /** * Never add stacktrace information. */ NEVER, /** * Always add stacktrace information. */ ALWAYS, /** * Add stacktrace information when the "trace" request parameter is * "true". */ ON_TRACE_PARAM } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/config/Ssl.java
core/src/test/java/com/taobao/arthas/core/config/Ssl.java
package com.taobao.arthas.core.config; import java.util.Arrays; public class Ssl { String protocol; boolean enabled; Boolean testBoolean; Long testLong; Double testDouble; String[] ciphers; public String[] getCiphers() { return ciphers; } public void setCiphers(String[] ciphers) { this.ciphers = ciphers; } public Long getTestLong() { return testLong; } public void setTestLong(Long testLong) { this.testLong = testLong; } public Double getTestDouble() { return testDouble; } public void setTestDouble(Double testDouble) { this.testDouble = testDouble; } public Boolean getTestBoolean() { return testBoolean; } public void setTestBoolean(Boolean testBoolean) { this.testBoolean = testBoolean; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } @Override public String toString() { return "Ssl [protocol=" + protocol + ", enabled=" + enabled + ", testBoolean=" + testBoolean + ", testLong=" + testLong + ", testDouble=" + testDouble + ", ciphers=" + Arrays.toString(ciphers) + "]"; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/config/Server.java
core/src/test/java/com/taobao/arthas/core/config/Server.java
package com.taobao.arthas.core.config; import java.net.InetAddress; @Config(prefix = "server") public class Server { int port; String host; InetAddress address; boolean flag; @NestedConfig Ssl ssl; @NestedConfig ErrorProperties error; public InetAddress getAddress() { return address; } public void setAddress(InetAddress address) { this.address = address; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } @Override public String toString() { return "Server [port=" + port + ", host=" + host + ", address=" + address + ", flag=" + flag + ", ssl=" + ssl + ", error=" + error + "]"; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/config/SystemObject.java
core/src/test/java/com/taobao/arthas/core/config/SystemObject.java
package com.taobao.arthas.core.config; @Config(prefix = "system.test") public class SystemObject { String systemKey; int systemIngeger; String nonSystemKey; public String getSystemKey() { return systemKey; } public void setSystemKey(String systemKey) { this.systemKey = systemKey; } public int getSystemIngeger() { return systemIngeger; } public void setSystemIngeger(int systemIngeger) { this.systemIngeger = systemIngeger; } public String getNonSystemKey() { return nonSystemKey; } public void setNonSystemKey(String nonSystemKey) { this.nonSystemKey = nonSystemKey; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/config/PropertiesInjectUtilTest.java
core/src/test/java/com/taobao/arthas/core/config/PropertiesInjectUtilTest.java
package com.taobao.arthas.core.config; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Properties; import org.junit.Assert; import org.junit.Test; import com.taobao.arthas.core.config.ErrorProperties.IncludeStacktrace; import com.taobao.arthas.core.env.ArthasEnvironment; import com.taobao.arthas.core.env.PropertiesPropertySource; public class PropertiesInjectUtilTest { @Test public void test() throws UnknownHostException { Properties p = new Properties(); p.put("server.port", "8080"); p.put("server.host", "localhost"); p.put("server.flag", "true"); p.put("server.address", "192.168.1.1"); p.put("server.ssl.enabled", "true"); p.put("server.ssl.protocol", "TLS"); p.put("server.ssl.testBoolean", "false"); p.put("server.ssl.testLong", "123"); p.put("server.ssl.ciphers", "abc, efg ,hij"); p.put("server.error.includeStacktrace", "ALWAYS"); ArthasEnvironment arthasEnvironment = new ArthasEnvironment(); arthasEnvironment.addLast(new PropertiesPropertySource("test1", p)); Server server = new Server(); BinderUtils.inject(arthasEnvironment, server); System.out.println(server); Assert.assertEquals(server.getPort(), 8080); Assert.assertEquals(server.getHost(), "localhost"); Assert.assertTrue(server.isFlag()); Assert.assertEquals(server.getAddress(), InetAddress.getByName("192.168.1.1")); Assert.assertEquals(server.ssl.getProtocol(), "TLS"); Assert.assertTrue(server.ssl.isEnabled()); Assert.assertFalse(server.ssl.getTestBoolean()); Assert.assertEquals(server.ssl.getTestLong(), Long.valueOf(123)); Assert.assertNull(server.ssl.getTestDouble()); Assert.assertArrayEquals(server.ssl.getCiphers(), new String[] { "abc", "efg", "hij" }); Assert.assertEquals(server.error.getIncludeStacktrace(), IncludeStacktrace.ALWAYS); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/config/ServerPropertiesTest.java
core/src/test/java/com/taobao/arthas/core/config/ServerPropertiesTest.java
package com.taobao.arthas.core.config; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Properties; import org.junit.Assert; import org.junit.Test; import com.taobao.arthas.core.config.ErrorProperties.IncludeStacktrace; import com.taobao.arthas.core.env.ArthasEnvironment; import com.taobao.arthas.core.env.PropertiesPropertySource; public class ServerPropertiesTest { @Test public void test() throws UnknownHostException { Properties p = new Properties(); p.put("server.port", "8080"); p.put("server.address", "192.168.1.1"); p.put("server.ssl.enabled", "true"); p.put("server.ssl.protocol", "TLS"); p.put("server.ssl.ciphers", "abc, efg ,hij"); p.put("server.error.includeStacktrace", "ALWAYS"); ArthasEnvironment arthasEnvironment = new ArthasEnvironment(); arthasEnvironment.addLast(new PropertiesPropertySource("test1", p)); ServerProperties serverProperties = new ServerProperties(); BinderUtils.inject(arthasEnvironment, serverProperties); Assert.assertEquals(serverProperties.getPort().intValue(), 8080); Assert.assertEquals(serverProperties.getAddress(), InetAddress.getByName("192.168.1.1")); Assert.assertEquals(serverProperties.getSsl().getProtocol(), "TLS"); Assert.assertTrue(serverProperties.getSsl().isEnabled()); Assert.assertArrayEquals(serverProperties.getSsl().getCiphers(), new String[] { "abc", "efg", "hij" }); Assert.assertEquals(serverProperties.getError().getIncludeStacktrace(), IncludeStacktrace.ALWAYS); } @Test public void testSystemProperties() { Properties p = new Properties(); p.put("system.test.systemKey", "kkk"); p.put("system.test.nonSystemKey", "xxxx"); p.put("system.test.systemIngeger", "123"); System.setProperty("system.test.systemKey", "ssss"); System.setProperty("system.test.systemIngeger", "110"); ArthasEnvironment arthasEnvironment = new ArthasEnvironment(); arthasEnvironment.addLast(new PropertiesPropertySource("test1", p)); SystemObject systemObject = new SystemObject(); BinderUtils.inject(arthasEnvironment, systemObject); Assert.assertEquals(systemObject.getSystemKey(), "ssss"); Assert.assertEquals(systemObject.getNonSystemKey(), "xxxx"); Assert.assertEquals(systemObject.getSystemIngeger(), 110); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/config/ServerProperties.java
core/src/test/java/com/taobao/arthas/core/config/ServerProperties.java
package com.taobao.arthas.core.config; import java.net.InetAddress; @Config(prefix = "server") public class ServerProperties { /** * Server HTTP port. */ private Integer port; /** * Network address to which the server should bind to. */ private InetAddress address; /** * Context path of the application. */ private String contextPath; /** * Display name of the application. */ private String displayName = "application"; @NestedConfig private ErrorProperties error = new ErrorProperties(); @NestedConfig private Ssl ssl; public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public InetAddress getAddress() { return address; } public void setAddress(InetAddress address) { this.address = address; } public String getContextPath() { return contextPath; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public ErrorProperties getError() { return error; } public void setError(ErrorProperties error) { this.error = error; } public Ssl getSsl() { return ssl; } public void setSsl(Ssl ssl) { this.ssl = ssl; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/testtool/TestUtils.java
core/src/test/java/com/taobao/arthas/core/testtool/TestUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.testtool; import org.junit.Assert; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author earayu */ public class TestUtils { public static <T> List<T> newArrayList(T ... items){ List<T> list = new ArrayList<T>(); if(items!=null) { Collections.addAll(list, items); } return list; } /** * copied from https://github.com/apache/commons-io/blob/master/src/test/java/org/apache/commons/io/testtools/TestUtils.java * Assert that the content of a file is equal to that in a byte[]. * * @param b0 the expected contents * @param file the file to check * @throws IOException If an I/O error occurs while reading the file contents */ public static void assertEqualContent(final byte[] b0, final File file) throws IOException { int count = 0, numRead = 0; final byte[] b1 = new byte[b0.length]; InputStream is = null; try { is = new FileInputStream(file); while (count < b0.length && numRead >= 0) { numRead = is.read(b1, count, b0.length); count += numRead; } Assert.assertEquals("Different number of bytes: ", b0.length, count); for (int i = 0; i < count; i++) { Assert.assertEquals("byte " + i + " differs", b0[i], b1[i]); } }finally { if(is!=null){ is.close(); } } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/shell/command/internal/GrepHandlerTest.java
core/src/test/java/com/taobao/arthas/core/shell/command/internal/GrepHandlerTest.java
package com.taobao.arthas.core.shell.command.internal; import org.junit.Assert; import org.junit.Test; public class GrepHandlerTest { @Test public void test4grep_ABC() { // -A -B -C Object[][] samples = new Object[][] { { "ABC\n1\n2\n3\n4\nc", "ABC", 0, 4, "ABC\n1\n2\n3\n4" }, { "ABC\n1\n2\n3\n4\nABC\n5", "ABC", 2, 1, "ABC\n1\n3\n4\nABC\n5" }, { "ABC\n1\n2\n3\n4\na", "ABC", 2, 1, "ABC\n1" }, { "ABC\n1\n2\n3\n4\nb", "ABC", 0, 0, "ABC" }, { "ABC\n1\n2\n3\n4\nc", "ABC", 0, 5, "ABC\n1\n2\n3\n4\nc" }, { "ABC\n1\n2\n3\n4\nc", "ABC", 0, 10, "ABC\n1\n2\n3\n4\nc" }, { "ABC\n1\n2\n3\n4\nc", "ABC", 0, 2, "ABC\n1\n2" }, { "1\n2\n3\n4\nABC", "ABC", 5, 1, "1\n2\n3\n4\nABC" }, { "1\n2\n3\n4\nABC", "ABC", 4, 1, "1\n2\n3\n4\nABC" }, { "1\n2\n3\n4\nABC", "ABC", 2, 1, "3\n4\nABC" } }; for (Object[] args : samples) { String word = (String) args[1]; int beforeLines = (Integer) args[2]; int afterLines = (Integer) args[3]; GrepHandler handler = new GrepHandler(word, false, false, true, false, true, beforeLines, afterLines, 0); String input = (String) args[0]; final String ret = handler.apply(input); final String expected = (String) args[4]; Assert.assertEquals(expected, ret.substring(0, ret.length() - 1)); } } @Test public void test4grep_v() {// -v Object[][] samples = new Object[][] { { "ABC\n1\n2\nc", "ABC", 0, 4, "1\n2\nc" }, { "ABC\n1\n2\n", "ABC", 0, 0, "1\n2" }, { "ABC\n1\n2\nc", "ABC", 0, 1, "1\n2\nc" } }; for (Object[] args : samples) { String word = (String) args[1]; int beforeLines = (Integer) args[2]; int afterLines = (Integer) args[3]; GrepHandler handler = new GrepHandler(word, false, true, true, false, true, beforeLines, afterLines, 0); String input = (String) args[0]; final String ret = handler.apply(input); final String expected = (String) args[4]; Assert.assertEquals(expected, ret.substring(0, ret.length() - 1)); } } @Test public void test4grep_e() {// -e Object[][] samples = new Object[][] { { "java\n1python\n2\nc", "java|python", "java\n1python" }, { "java\n1python\n2\nc", "ja|py", "java\n1python" } }; for (Object[] args : samples) { String word = (String) args[1]; GrepHandler handler = new GrepHandler(word, false, false, true, false, true, 0, 0, 0); String input = (String) args[0]; final String ret = handler.apply(input); final String expected = (String) args[2]; Assert.assertEquals(expected, ret.substring(0, ret.length() - 1)); } } @Test public void test4grep_m() {// -e Object[][] samples = new Object[][] { { "java\n1python\n2\nc", "java|python", "java", 1 }, { "java\n1python\n2\nc", "ja|py", "java\n1python", 2 }, { "java\n1python\n2\nc", "ja|py", "java\n1python", 3 } }; for (Object[] args : samples) { String word = (String) args[1]; int maxCount = args.length > 3 ? (Integer) args[3] : 0; GrepHandler handler = new GrepHandler(word, false, false, true, false, true, 0, 0, maxCount); String input = (String) args[0]; final String ret = handler.apply(input); final String expected = (String) args[2]; Assert.assertEquals(expected, ret.substring(0, ret.length() - 1)); } } @Test public void test4grep_n() {// -n Object[][] samples = new Object[][] { { "java\n1\npython\n2\nc", "1:java\n3:python", "java|python" }, { "java\n1\npython\njava\nc", "1:java\n4:java", "java", false } }; for (Object[] args : samples) { String word = (String) args[2]; boolean regexpMode = args.length > 3 ? (Boolean) args[3] : true; GrepHandler handler = new GrepHandler(word, false, false, regexpMode, true, true, 0, 0, 0); String input = (String) args[0]; final String ret = handler.apply(input); final String expected = (String) args[1]; Assert.assertEquals(expected, ret.substring(0, ret.length() - 1)); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/shell/cli/impl/CliTokenImplTest.java
core/src/test/java/com/taobao/arthas/core/shell/cli/impl/CliTokenImplTest.java
package com.taobao.arthas.core.shell.cli.impl; import com.taobao.arthas.core.shell.cli.CliToken; import org.junit.Assert; import org.junit.Test; import java.util.Iterator; import java.util.List; public class CliTokenImplTest { /** * supported: * <p> * case1: * thread| grep xxx * [thread|, grep, xxx] -> [thread, |, grep, xxx] * case:2 * thread | grep xxx * [thread, |, grep, xxx] -> [thread, |, grep, xxx] * case3: * thread |grep xxx * [thread, |grep] -> [thread, |, grep, xxx] */ @Test public void testSupportedPipeCharWithoutRegex() { String[] expectedTextTokenValue = new String[]{"thread", "|", "grep", "xxx"}; List<CliToken> actualTokens = CliTokenImpl.tokenize("thread| grep xxx"); assertEquals(expectedTextTokenValue, actualTokens); actualTokens = CliTokenImpl.tokenize("thread | grep xxx"); assertEquals(expectedTextTokenValue, actualTokens); actualTokens = CliTokenImpl.tokenize("thread |grep xxx"); assertEquals(expectedTextTokenValue, actualTokens); } /** * supported: * <p> * case1: * trace -E classA|classB methodA|methodB| grep classA * [trace, -E, classA|classB, methodA|methodB|, grep, classA] -> [trace, -E, classA|classB, methodA|methodB, |, grep, classA] * case2: * trace -E classA|classB methodA|methodB | grep classA * [trace, -E, classA|classB, methodA|methodB, |, grep, classA] -> [trace, -E, classA|classB, methodA|methodB, |, grep, classA] * case3: * trace -E classA|classB methodA|methodB |grep classA * [trace, -E, classA|classB, methodA|methodB, |grep, classA] -> [trace, -E, classA|classB, methodA|methodB, |, grep, classA] */ @Test public void testSupportedPipeCharWithRegex() { String[] expectedTextTokenValue = new String[]{"trace", "-E", "classA|classB", "methodA|methodB", "|", "grep", "classA"}; List<CliToken> actualTokens = CliTokenImpl.tokenize("trace -E classA|classB methodA|methodB| grep classA"); assertEquals(expectedTextTokenValue, actualTokens); actualTokens = CliTokenImpl.tokenize("trace -E classA|classB methodA|methodB | grep classA"); assertEquals(expectedTextTokenValue, actualTokens); actualTokens = CliTokenImpl.tokenize("trace -E classA|classB methodA|methodB |grep classA"); assertEquals(expectedTextTokenValue, actualTokens); } /** * unsupported: * <p> * case1: * thread|grep xxx * [thread|grep, xxx] -> [thread|grep, xxx] * case2: * trace -E classA|classB methodA|methodB|grep classA * [trace, -E, classA|classB, methodA|methodB|grep, classA] -> [trace, -E, classA|classB, methodA|methodB|grep, classA] * case3: * trace -E classA|classB| methodA|methodB | grep classA * [trace, -E, classA|classB|, methodA|methodB, |, grep, classA] -> [trace, -E, classA|classB,|, methodA|methodB, |, grep, classA] */ @Test public void testUnSupportedPipeChar() { String[] expectedTextTokenValue = new String[]{"thread|grep", "xxx"}; List<CliToken> actualTokens = CliTokenImpl.tokenize("thread|grep xxx"); assertEquals(expectedTextTokenValue, actualTokens); expectedTextTokenValue = new String[]{"trace", "-E", "classA|classB", "methodA|methodB|grep", "classA"}; actualTokens = CliTokenImpl.tokenize("trace -E classA|classB methodA|methodB|grep classA"); assertEquals(expectedTextTokenValue, actualTokens); expectedTextTokenValue = new String[]{"trace", "-E", "classA|classB", "|", "methodA|methodB", "|", "grep", "classA"}; actualTokens = CliTokenImpl.tokenize("trace -E classA|classB| methodA|methodB | grep classA"); assertEquals(expectedTextTokenValue, actualTokens); } private void assertEquals(String[] expectedTextTokenValue, List<CliToken> actualTokens) { removeBlankToken(actualTokens); for (int i = 0; i < expectedTextTokenValue.length; i++) { Assert.assertEquals(expectedTextTokenValue[i], actualTokens.get(i).value()); } } private void removeBlankToken(List<CliToken> cliTokens) { CliToken blankToken = new CliTokenImpl(false, " "); Iterator<CliToken> it = cliTokens.iterator(); while (it.hasNext()) { CliToken token = it.next(); if (blankToken.equals(token)) { it.remove(); } } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/test/java/com/taobao/arthas/core/mcp/tool/function/basic1000/ViewFileToolTest.java
core/src/test/java/com/taobao/arthas/core/mcp/tool/function/basic1000/ViewFileToolTest.java
package com.taobao.arthas.core.mcp.tool.function.basic1000; import com.fasterxml.jackson.core.type.TypeReference; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.util.JsonParser; import org.junit.*; import org.junit.rules.TemporaryFolder; import java.io.File; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Base64; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; public class ViewFileToolTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); private final ToolContext toolContext = new ToolContext(Collections.emptyMap()); private final ViewFileTool tool = new ViewFileTool(); @Before public void setUp() { clearEnv(ViewFileTool.ALLOWED_DIRS_ENV); } @After public void tearDown() { clearEnv(ViewFileTool.ALLOWED_DIRS_ENV); } /** * 通过反射设置环境变量(仅用于测试) */ @SuppressWarnings("unchecked") private static void setEnv(String key, String value) { try { Map<String, String> env = System.getenv(); Field field = env.getClass().getDeclaredField("m"); field.setAccessible(true); Map<String, String> writableEnv = (Map<String, String>) field.get(env); writableEnv.put(key, value); } catch (Exception e) { throw new RuntimeException("Failed to set environment variable: " + key, e); } } /** * 通过反射清除环境变量(仅用于测试) */ @SuppressWarnings("unchecked") private static void clearEnv(String key) { try { Map<String, String> env = System.getenv(); Field field = env.getClass().getDeclaredField("m"); field.setAccessible(true); Map<String, String> writableEnv = (Map<String, String>) field.get(env); writableEnv.remove(key); } catch (Exception e) { // ignore } } @Test public void should_error_when_file_not_found_or_not_allowed() { String json = tool.viewFile("a.txt", null, null, 10, toolContext); Map<String, Object> result = parse(json); Assert.assertEquals("error", result.get("status")); Assert.assertNotNull(result.get("message")); } @Test public void should_read_file_in_chunks_with_cursor() throws Exception { File allowedDir = temporaryFolder.newFolder("allowed"); setEnv(ViewFileTool.ALLOWED_DIRS_ENV, allowedDir.getAbsolutePath()); Path file = allowedDir.toPath().resolve("test.txt"); Files.write(file, "abcdefghijklmnopqrstuvwxyz".getBytes(StandardCharsets.UTF_8)); Map<String, Object> first = parse(tool.viewFile("test.txt", null, 0L, 5, toolContext)); Assert.assertEquals("completed", first.get("status")); Assert.assertEquals("abcde", first.get("content")); String nextCursor = String.valueOf(first.get("nextCursor")); Assert.assertNotNull(nextCursor); Assert.assertFalse(nextCursor.trim().isEmpty()); Map<String, Object> second = parse(tool.viewFile(null, nextCursor, null, 5, toolContext)); Assert.assertEquals("completed", second.get("status")); Assert.assertEquals("fghij", second.get("content")); } @Test public void should_reject_absolute_path_outside_allowed_root() throws Exception { File allowedDir = temporaryFolder.newFolder("allowed"); setEnv(ViewFileTool.ALLOWED_DIRS_ENV, allowedDir.getAbsolutePath()); File outside = temporaryFolder.newFile("outside.txt"); Files.write(outside.toPath(), "outside".getBytes(StandardCharsets.UTF_8)); Map<String, Object> result = parse(tool.viewFile(outside.getAbsolutePath(), null, 0L, 10, toolContext)); Assert.assertEquals("error", result.get("status")); } @Test public void should_reject_path_traversal_outside_allowed_root() throws Exception { File allowedDir = temporaryFolder.newFolder("allowed"); setEnv(ViewFileTool.ALLOWED_DIRS_ENV, allowedDir.getAbsolutePath()); File outside = temporaryFolder.newFile("outside.txt"); Files.write(outside.toPath(), "outside".getBytes(StandardCharsets.UTF_8)); Map<String, Object> result = parse(tool.viewFile("../outside.txt", null, 0L, 10, toolContext)); Assert.assertEquals("error", result.get("status")); } @Test public void should_reject_cursor_tampering_outside_allowed_root() throws Exception { File allowedDir = temporaryFolder.newFolder("allowed"); setEnv(ViewFileTool.ALLOWED_DIRS_ENV, allowedDir.getAbsolutePath()); File outside = temporaryFolder.newFile("outside.txt"); Files.write(outside.toPath(), "outside".getBytes(StandardCharsets.UTF_8)); Map<String, Object> cursor = new LinkedHashMap<>(); cursor.put("v", 1); cursor.put("path", outside.getAbsolutePath()); cursor.put("offset", 0); String cursorJson = JsonParser.toJson(cursor); String encodedCursor = Base64.getUrlEncoder().withoutPadding() .encodeToString(cursorJson.getBytes(StandardCharsets.UTF_8)); Map<String, Object> result = parse(tool.viewFile(null, encodedCursor, null, 10, toolContext)); Assert.assertEquals("error", result.get("status")); } @Test public void should_error_for_negative_offset() throws Exception { File allowedDir = temporaryFolder.newFolder("allowed"); setEnv(ViewFileTool.ALLOWED_DIRS_ENV, allowedDir.getAbsolutePath()); Path file = allowedDir.toPath().resolve("test.txt"); Files.write(file, "abc".getBytes(StandardCharsets.UTF_8)); Map<String, Object> result = parse(tool.viewFile("test.txt", null, -1L, 10, toolContext)); Assert.assertEquals("error", result.get("status")); } @Test public void should_reject_symlink_escape() throws Exception { File allowedDir = temporaryFolder.newFolder("allowed"); setEnv(ViewFileTool.ALLOWED_DIRS_ENV, allowedDir.getAbsolutePath()); File outside = temporaryFolder.newFile("outside.txt"); Files.write(outside.toPath(), "outside".getBytes(StandardCharsets.UTF_8)); Path link = allowedDir.toPath().resolve("link.txt"); try { Files.createSymbolicLink(link, outside.toPath()); } catch (UnsupportedOperationException e) { Assume.assumeNoException("当前平台不支持创建符号链接,跳过", e); } catch (Exception e) { Assume.assumeNoException("创建符号链接失败,跳过", e); } Map<String, Object> result = parse(tool.viewFile("link.txt", null, 0L, 10, toolContext)); Assert.assertEquals("error", result.get("status")); } private static Map<String, Object> parse(String json) { return JsonParser.fromJson(json, new TypeReference<Map<String, Object>>() {}); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/GlobalOptions.java
core/src/main/java/com/taobao/arthas/core/GlobalOptions.java
package com.taobao.arthas.core; import java.lang.reflect.Field; import com.taobao.arthas.common.JavaVersionUtils; import com.taobao.arthas.common.UnsafeUtils; import ognl.OgnlRuntime; /** * 全局开关 * Created by vlinux on 15/6/4. */ public class GlobalOptions { public static final String STRICT_MESSAGE = "By default, strict mode is true, " + "not allowed to set object properties. " + "Want to set object properties, execute `options strict false`"; /** * 是否支持系统类<br/> * 这个开关打开之后将能代理到来自JVM的部分类,由于有非常强的安全风险可能会引起系统崩溃<br/> * 所以这个开关默认是关闭的,除非你非常了解你要做什么,否则请不要打开 */ @Option(level = 0, name = "unsafe", summary = "Option to support system-level class", description = "This option enables to proxy functionality of JVM classes." + " Due to serious security risk a JVM crash is possibly be introduced." + " Do not activate it unless you are able to manage." ) public static volatile boolean isUnsafe = false; /** * 是否支持dump被增强的类<br/> * 这个开关打开这后,每次增强类的时候都将会将增强的类dump到文件中,以便于进行反编译分析 */ @Option(level = 1, name = "dump", summary = "Option to dump the enhanced classes", description = "This option enables the enhanced classes to be dumped to external file " + "for further de-compilation and analysis." ) public static volatile boolean isDump = false; /** * 是否支持批量增强<br/> * 这个开关打开后,每次均是批量增强类 */ @Option(level = 1, name = "batch-re-transform", summary = "Option to support batch reTransform Class", description = "This options enables to reTransform classes with batch mode." ) public static volatile boolean isBatchReTransform = true; /** * 是否支持json格式化输出<br/> * 这个开关打开后,使用json格式输出目标对象,配合-x参数使用 */ @Option(level = 2, name = "json-format", summary = "Option to support JSON format of object output", description = "This option enables to format object output with JSON when -x option selected." ) public static volatile boolean isUsingJson = false; /** * 是否关闭子类 */ @Option( level = 1, name = "disable-sub-class", summary = "Option to control include sub class when class matching", description = "This option disable to include sub class when matching class." ) public static volatile boolean isDisableSubClass = false; /** * 是否在interface类里搜索函数 * https://github.com/alibaba/arthas/issues/1105 */ @Option( level = 1, name = "support-default-method", summary = "Option to control include default method in interface when class matching", description = "This option disable to include default method in interface when matching class." ) public static volatile boolean isSupportDefaultMethod = JavaVersionUtils.isGreaterThanJava7(); /** * 是否日志中保存命令执行结果 */ @Option(level = 1, name = "save-result", summary = "Option to print command's result to log file", description = "This option enables to save each command's result to log file, " + "which path is ${user.home}/logs/arthas-cache/result.log." ) public static volatile boolean isSaveResult = false; /** * job的超时时间 */ @Option(level = 2, name = "job-timeout", summary = "Option to job timeout", description = "This option setting job timeout,The unit can be d, h, m, s for day, hour, minute, second. " + "1d is one day in default" ) public static volatile String jobTimeout = "1d"; /** * 是否打印parent类里的field * @see com.taobao.arthas.core.view.ObjectView */ @Option(level = 1, name = "print-parent-fields", summary = "Option to print all fileds in parent class", description = "This option enables print files in parent class, default value true." ) public static volatile boolean printParentFields = true; /** * 是否打开verbose 开关 */ @Option(level = 1, name = "verbose", summary = "Option to print verbose information", description = "This option enables print verbose information, default value false." ) public static volatile boolean verbose = false; /** * 是否打开strict 开关。更新时注意 ognl 里的配置需要同步修改 * @see ognl.OgnlRuntime#getUseStricterInvocationValue() */ @Option(level = 1, name = "strict", summary = "Option to strict mode", description = STRICT_MESSAGE ) public static volatile boolean strict = true; public static void updateOnglStrict(boolean strict) { try { Field field = OgnlRuntime.class.getDeclaredField("_useStricterInvocation"); field.setAccessible(true); // 获取字段的内存偏移量和基址 Object staticFieldBase = UnsafeUtils.UNSAFE.staticFieldBase(field); long staticFieldOffset = UnsafeUtils.UNSAFE.staticFieldOffset(field); // 修改字段的值 UnsafeUtils.UNSAFE.putBoolean(staticFieldBase, staticFieldOffset, strict); } catch (NoSuchFieldException | SecurityException e) { // ignore } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/Arthas.java
core/src/main/java/com/taobao/arthas/core/Arthas.java
package com.taobao.arthas.core; import com.sun.tools.attach.VirtualMachine; import com.sun.tools.attach.VirtualMachineDescriptor; import com.taobao.arthas.common.AnsiLog; import com.taobao.arthas.common.ArthasConstants; import com.taobao.arthas.common.JavaVersionUtils; import com.taobao.arthas.core.config.Configure; import com.taobao.middleware.cli.CLI; import com.taobao.middleware.cli.CLIs; import com.taobao.middleware.cli.CommandLine; import com.taobao.middleware.cli.Option; import com.taobao.middleware.cli.TypedOption; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; import java.util.Properties; /** * Arthas启动器 */ public class Arthas { private Arthas(String[] args) throws Exception { attachAgent(parse(args)); } private Configure parse(String[] args) { Option pid = new TypedOption<Long>().setType(Long.class).setShortName("pid").setRequired(true); Option core = new TypedOption<String>().setType(String.class).setShortName("core").setRequired(true); Option agent = new TypedOption<String>().setType(String.class).setShortName("agent").setRequired(true); Option target = new TypedOption<String>().setType(String.class).setShortName("target-ip"); Option telnetPort = new TypedOption<Integer>().setType(Integer.class) .setShortName("telnet-port"); Option httpPort = new TypedOption<Integer>().setType(Integer.class) .setShortName("http-port"); Option sessionTimeout = new TypedOption<Integer>().setType(Integer.class) .setShortName("session-timeout"); Option username = new TypedOption<String>().setType(String.class).setShortName("username"); Option password = new TypedOption<String>().setType(String.class).setShortName("password"); Option tunnelServer = new TypedOption<String>().setType(String.class).setShortName("tunnel-server"); Option agentId = new TypedOption<String>().setType(String.class).setShortName("agent-id"); Option appName = new TypedOption<String>().setType(String.class).setShortName(ArthasConstants.APP_NAME); Option statUrl = new TypedOption<String>().setType(String.class).setShortName("stat-url"); Option disabledCommands = new TypedOption<String>().setType(String.class).setShortName("disabled-commands"); CLI cli = CLIs.create("arthas").addOption(pid).addOption(core).addOption(agent).addOption(target) .addOption(telnetPort).addOption(httpPort).addOption(sessionTimeout) .addOption(username).addOption(password) .addOption(tunnelServer).addOption(agentId).addOption(appName).addOption(statUrl).addOption(disabledCommands); CommandLine commandLine = cli.parse(Arrays.asList(args)); Configure configure = new Configure(); configure.setJavaPid((Long) commandLine.getOptionValue("pid")); configure.setArthasAgent((String) commandLine.getOptionValue("agent")); configure.setArthasCore((String) commandLine.getOptionValue("core")); if (commandLine.getOptionValue("session-timeout") != null) { configure.setSessionTimeout((Integer) commandLine.getOptionValue("session-timeout")); } if (commandLine.getOptionValue("target-ip") != null) { configure.setIp((String) commandLine.getOptionValue("target-ip")); } if (commandLine.getOptionValue("telnet-port") != null) { configure.setTelnetPort((Integer) commandLine.getOptionValue("telnet-port")); } if (commandLine.getOptionValue("http-port") != null) { configure.setHttpPort((Integer) commandLine.getOptionValue("http-port")); } configure.setUsername((String) commandLine.getOptionValue("username")); configure.setPassword((String) commandLine.getOptionValue("password")); configure.setTunnelServer((String) commandLine.getOptionValue("tunnel-server")); configure.setAgentId((String) commandLine.getOptionValue("agent-id")); configure.setStatUrl((String) commandLine.getOptionValue("stat-url")); configure.setDisabledCommands((String) commandLine.getOptionValue("disabled-commands")); configure.setAppName((String) commandLine.getOptionValue(ArthasConstants.APP_NAME)); return configure; } private void attachAgent(Configure configure) throws Exception { VirtualMachineDescriptor virtualMachineDescriptor = null; for (VirtualMachineDescriptor descriptor : VirtualMachine.list()) { String pid = descriptor.id(); if (pid.equals(Long.toString(configure.getJavaPid()))) { virtualMachineDescriptor = descriptor; break; } } VirtualMachine virtualMachine = null; try { if (null == virtualMachineDescriptor) { // 使用 attach(String pid) 这种方式 virtualMachine = VirtualMachine.attach("" + configure.getJavaPid()); } else { virtualMachine = VirtualMachine.attach(virtualMachineDescriptor); } Properties targetSystemProperties = virtualMachine.getSystemProperties(); String targetJavaVersion = JavaVersionUtils.javaVersionStr(targetSystemProperties); String currentJavaVersion = JavaVersionUtils.javaVersionStr(); if (targetJavaVersion != null && currentJavaVersion != null) { if (!targetJavaVersion.equals(currentJavaVersion)) { AnsiLog.warn("Current VM java version: {} do not match target VM java version: {}, attach may fail.", currentJavaVersion, targetJavaVersion); AnsiLog.warn("Target VM JAVA_HOME is {}, arthas-boot JAVA_HOME is {}, try to set the same JAVA_HOME.", targetSystemProperties.getProperty("java.home"), System.getProperty("java.home")); } } String arthasAgentPath = configure.getArthasAgent(); //convert jar path to unicode string configure.setArthasAgent(encodeArg(arthasAgentPath)); configure.setArthasCore(encodeArg(configure.getArthasCore())); try { virtualMachine.loadAgent(arthasAgentPath, configure.getArthasCore() + ";" + configure.toString()); } catch (IOException e) { if (e.getMessage() != null && e.getMessage().contains("Non-numeric value found")) { AnsiLog.warn(e); AnsiLog.warn("It seems to use the lower version of JDK to attach the higher version of JDK."); AnsiLog.warn( "This error message can be ignored, the attach may have been successful, and it will still try to connect."); } else { throw e; } } catch (com.sun.tools.attach.AgentLoadException ex) { if ("0".equals(ex.getMessage())) { // https://stackoverflow.com/a/54454418 AnsiLog.warn(ex); AnsiLog.warn("It seems to use the higher version of JDK to attach the lower version of JDK."); AnsiLog.warn( "This error message can be ignored, the attach may have been successful, and it will still try to connect."); } else { throw ex; } } } finally { if (null != virtualMachine) { virtualMachine.detach(); } } } private static String encodeArg(String arg) { try { return URLEncoder.encode(arg, "utf-8"); } catch (UnsupportedEncodingException e) { return arg; } } public static void main(String[] args) { try { new Arthas(args); } catch (Throwable t) { AnsiLog.error("Start arthas failed, exception stack trace: "); t.printStackTrace(); System.exit(-1); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/Option.java
core/src/main/java/com/taobao/arthas/core/Option.java
package com.taobao.arthas.core; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Arthas全局选项 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Option { /* * 选项级别,数字越小级别越高 */ int level(); /* * 选项名称 */ String name(); /* * 选项摘要说明 */ String summary(); /* * 命令描述 */ String description(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/UserStatUtil.java
core/src/main/java/com/taobao/arthas/core/util/UserStatUtil.java
package com.taobao.arthas.core.util; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; /** * Arthas 使用情况统计 * <p/> * Created by zhuyong on 15/11/12. */ public class UserStatUtil { private static final int DEFAULT_BUFFER_SIZE = 8192; private static final byte[] SKIP_BYTE_BUFFER = new byte[DEFAULT_BUFFER_SIZE]; private static final ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { final Thread t = new Thread(r, "arthas-UserStat"); t.setDaemon(true); return t; } }); private static final String ip = IPUtils.getLocalIP(); private static final String version = URLEncoder.encode(ArthasBanner.version().replace("\n", "")); private static volatile String statUrl = null; private static volatile String agentId = null; public static String getStatUrl() { return statUrl; } public static void setStatUrl(String url) { statUrl = url; } public static String getAgentId() { return agentId; } public static void setAgentId(String id) { agentId = id; } public static void arthasStart() { if (statUrl == null) { return; } RemoteJob job = new RemoteJob(); job.appendQueryData("ip", ip); job.appendQueryData("version", version); if (agentId != null) { job.appendQueryData("agentId", agentId); } job.appendQueryData("command", "start"); try { executorService.execute(job); } catch (Throwable t) { // } } private static void arthasUsage(String cmd, String detail, String userId) { RemoteJob job = new RemoteJob(); job.appendQueryData("ip", ip); job.appendQueryData("version", version); if (agentId != null) { job.appendQueryData("agentId", agentId); } if (userId != null) { job.appendQueryData("userId", URLEncoder.encode(userId)); } job.appendQueryData("command", URLEncoder.encode(cmd)); if (detail != null) { job.appendQueryData("arguments", URLEncoder.encode(detail)); } try { executorService.execute(job); } catch (Throwable t) { // } } /** * Report command usage with userId * * @param cmd command name * @param args command arguments * @param userId user id */ public static void arthasUsageSuccess(String cmd, List<String> args, String userId) { if (statUrl == null) { return; } StringBuilder commandString = new StringBuilder(cmd); for (String arg : args) { commandString.append(" ").append(arg); } UserStatUtil.arthasUsage(cmd, commandString.toString(), userId); } public static void arthasUsageSuccess(String cmd, List<String> args) { arthasUsageSuccess(cmd, args, null); } public static void destroy() { // 直接关闭,没有回报的丢弃 executorService.shutdownNow(); } static class RemoteJob implements Runnable { private StringBuilder queryData = new StringBuilder(); public void appendQueryData(String key, String value) { if (key != null && value != null) { if (queryData.length() == 0) { queryData.append(key).append("=").append(value); } else { queryData.append("&").append(key).append("=").append(value); } } } @Override public void run() { String link = statUrl; if (link == null) { return; } InputStream inputStream = null; try { if (queryData.length() != 0) { link = link + "?" + queryData; } URL url = new URL(link); URLConnection connection = url.openConnection(); connection.setConnectTimeout(1000); connection.setReadTimeout(1000); connection.connect(); inputStream = connection.getInputStream(); //noinspection StatementWithEmptyBody while (inputStream.read(SKIP_BYTE_BUFFER) != -1) { // do nothing } } catch (Throwable t) { // ignore } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // ignore } } } } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/IPUtils.java
core/src/main/java/com/taobao/arthas/core/util/IPUtils.java
package com.taobao.arthas.core.util; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; /** * @author weipeng2k 2015-01-30 15:06:47 */ public class IPUtils { private static final String WINDOWS = "windows"; private static final String OS_NAME = "os.name"; /** * check: whether current operating system is windows * * @return true---is windows */ public static boolean isWindowsOS() { String osName = System.getProperty(OS_NAME); return osName.toLowerCase().contains(WINDOWS); } /** * get IP address, automatically distinguish the operating system.(windows or * linux) * * @return String */ public static String getLocalIP() { InetAddress ip = null; try { if (isWindowsOS()) { ip = InetAddress.getLocalHost(); } else { // scan all NetWorkInterfaces if it's loopback address if (!InetAddress.getLocalHost().isLoopbackAddress()) { ip = InetAddress.getLocalHost(); } else { boolean bFindIP = false; Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces(); while (netInterfaces.hasMoreElements()) { if (bFindIP) { break; } NetworkInterface ni = netInterfaces.nextElement(); // ----------特定情况,可以考虑用ni.getName判断 // iterator all IPs Enumeration<InetAddress> ips = ni.getInetAddresses(); while (ips.hasMoreElements()) { ip = ips.nextElement(); // IP starts with 127. is loopback address if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().contains(":")) { bFindIP = true; break; } } } } } } catch (Exception e) { } return ip == null ? null : ip.getHostAddress(); } public static boolean isAllZeroIP(String ipStr) { if (ipStr == null || ipStr.isEmpty()) { return false; } char[] charArray = ipStr.toCharArray(); for (char c : charArray) { if (c != '0' && c != '.' && c != ':') { return false; } } return true; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/ObjectUtils.java
core/src/main/java/com/taobao/arthas/core/util/ObjectUtils.java
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.taobao.arthas.core.util; import java.lang.reflect.Array; import java.util.Arrays; public abstract class ObjectUtils { private static final int INITIAL_HASH = 7; private static final int MULTIPLIER = 31; private static final String EMPTY_STRING = ""; private static final String NULL_STRING = "null"; private static final String ARRAY_START = "{"; private static final String ARRAY_END = "}"; private static final String EMPTY_ARRAY = "{}"; private static final String ARRAY_ELEMENT_SEPARATOR = ", "; public ObjectUtils() { } public static boolean isCheckedException(Throwable ex) { return !(ex instanceof RuntimeException) && !(ex instanceof Error); } public static boolean isCompatibleWithThrowsClause(Throwable ex, Class... declaredExceptions) { if(!isCheckedException(ex)) { return true; } else { if(declaredExceptions != null) { Class[] var2 = declaredExceptions; int var3 = declaredExceptions.length; for(int var4 = 0; var4 < var3; ++var4) { Class declaredException = var2[var4]; if(declaredException.isInstance(ex)) { return true; } } } return false; } } public static boolean isArray(Object obj) { return obj != null && obj.getClass().isArray(); } public static boolean isEmpty(Object[] array) { return array == null || array.length == 0; } public static boolean containsElement(Object[] array, Object element) { if(array == null) { return false; } else { Object[] var2 = array; int var3 = array.length; for(int var4 = 0; var4 < var3; ++var4) { Object arrayEle = var2[var4]; if(nullSafeEquals(arrayEle, element)) { return true; } } return false; } } public static boolean containsConstant(Enum<?>[] enumValues, String constant) { return containsConstant(enumValues, constant, false); } public static boolean containsConstant(Enum<?>[] enumValues, String constant, boolean caseSensitive) { Enum[] var3 = enumValues; int var4 = enumValues.length; int var5 = 0; while(true) { if(var5 >= var4) { return false; } Enum candidate = var3[var5]; if(caseSensitive) { if(candidate.toString().equals(constant)) { break; } } else if(candidate.toString().equalsIgnoreCase(constant)) { break; } ++var5; } return true; } public static Object[] toObjectArray(Object source) { if(source instanceof Object[]) { return (Object[])((Object[])source); } else if(source == null) { return new Object[0]; } else if(!source.getClass().isArray()) { throw new IllegalArgumentException("Source is not an array: " + source); } else { int length = Array.getLength(source); if(length == 0) { return new Object[0]; } else { Class wrapperType = Array.get(source, 0).getClass(); Object[] newArray = (Object[])((Object[])Array.newInstance(wrapperType, length)); for(int i = 0; i < length; ++i) { newArray[i] = Array.get(source, i); } return newArray; } } } public static boolean nullSafeEquals(Object o1, Object o2) { if(o1 == o2) { return true; } else if(o1 != null && o2 != null) { if(o1.equals(o2)) { return true; } else { if(o1.getClass().isArray() && o2.getClass().isArray()) { if(o1 instanceof Object[] && o2 instanceof Object[]) { return Arrays.equals((Object[])((Object[])o1), (Object[])((Object[])o2)); } if(o1 instanceof boolean[] && o2 instanceof boolean[]) { return Arrays.equals((boolean[])((boolean[])o1), (boolean[])((boolean[])o2)); } if(o1 instanceof byte[] && o2 instanceof byte[]) { return Arrays.equals((byte[])((byte[])o1), (byte[])((byte[])o2)); } if(o1 instanceof char[] && o2 instanceof char[]) { return Arrays.equals((char[])((char[])o1), (char[])((char[])o2)); } if(o1 instanceof double[] && o2 instanceof double[]) { return Arrays.equals((double[])((double[])o1), (double[])((double[])o2)); } if(o1 instanceof float[] && o2 instanceof float[]) { return Arrays.equals((float[])((float[])o1), (float[])((float[])o2)); } if(o1 instanceof int[] && o2 instanceof int[]) { return Arrays.equals((int[])((int[])o1), (int[])((int[])o2)); } if(o1 instanceof long[] && o2 instanceof long[]) { return Arrays.equals((long[])((long[])o1), (long[])((long[])o2)); } if(o1 instanceof short[] && o2 instanceof short[]) { return Arrays.equals((short[])((short[])o1), (short[])((short[])o2)); } } return false; } } else { return false; } } public static int nullSafeHashCode(Object obj) { if(obj == null) { return 0; } else { if(obj.getClass().isArray()) { if(obj instanceof Object[]) { return nullSafeHashCode((Object[])((Object[])obj)); } if(obj instanceof boolean[]) { return nullSafeHashCode((boolean[])((boolean[])obj)); } if(obj instanceof byte[]) { return nullSafeHashCode((byte[])((byte[])obj)); } if(obj instanceof char[]) { return nullSafeHashCode((char[])((char[])obj)); } if(obj instanceof double[]) { return nullSafeHashCode((double[])((double[])obj)); } if(obj instanceof float[]) { return nullSafeHashCode((float[])((float[])obj)); } if(obj instanceof int[]) { return nullSafeHashCode((int[])((int[])obj)); } if(obj instanceof long[]) { return nullSafeHashCode((long[])((long[])obj)); } if(obj instanceof short[]) { return nullSafeHashCode((short[])((short[])obj)); } } return obj.hashCode(); } } public static int nullSafeHashCode(Object[] array) { if(array == null) { return 0; } else { int hash = 7; Object[] var2 = array; int var3 = array.length; for(int var4 = 0; var4 < var3; ++var4) { Object element = var2[var4]; hash = 31 * hash + nullSafeHashCode(element); } return hash; } } public static int nullSafeHashCode(boolean[] array) { if(array == null) { return 0; } else { int hash = 7; boolean[] var2 = array; int var3 = array.length; for(int var4 = 0; var4 < var3; ++var4) { boolean element = var2[var4]; hash = 31 * hash + hashCode(element); } return hash; } } public static int nullSafeHashCode(byte[] array) { if(array == null) { return 0; } else { int hash = 7; byte[] var2 = array; int var3 = array.length; for(int var4 = 0; var4 < var3; ++var4) { byte element = var2[var4]; hash = 31 * hash + element; } return hash; } } public static int nullSafeHashCode(char[] array) { if(array == null) { return 0; } else { int hash = 7; char[] var2 = array; int var3 = array.length; for(int var4 = 0; var4 < var3; ++var4) { char element = var2[var4]; hash = 31 * hash + element; } return hash; } } public static int nullSafeHashCode(double[] array) { if(array == null) { return 0; } else { int hash = 7; double[] var2 = array; int var3 = array.length; for(int var4 = 0; var4 < var3; ++var4) { double element = var2[var4]; hash = 31 * hash + hashCode(element); } return hash; } } public static int nullSafeHashCode(float[] array) { if(array == null) { return 0; } else { int hash = 7; float[] var2 = array; int var3 = array.length; for(int var4 = 0; var4 < var3; ++var4) { float element = var2[var4]; hash = 31 * hash + hashCode(element); } return hash; } } public static int nullSafeHashCode(int[] array) { if(array == null) { return 0; } else { int hash = 7; int[] var2 = array; int var3 = array.length; for(int var4 = 0; var4 < var3; ++var4) { int element = var2[var4]; hash = 31 * hash + element; } return hash; } } public static int nullSafeHashCode(long[] array) { if(array == null) { return 0; } else { int hash = 7; long[] var2 = array; int var3 = array.length; for(int var4 = 0; var4 < var3; ++var4) { long element = var2[var4]; hash = 31 * hash + hashCode(element); } return hash; } } public static int nullSafeHashCode(short[] array) { if(array == null) { return 0; } else { int hash = 7; short[] var2 = array; int var3 = array.length; for(int var4 = 0; var4 < var3; ++var4) { short element = var2[var4]; hash = 31 * hash + element; } return hash; } } public static int hashCode(boolean bool) { return bool?1231:1237; } public static int hashCode(double dbl) { return hashCode(Double.doubleToLongBits(dbl)); } public static int hashCode(float flt) { return Float.floatToIntBits(flt); } public static int hashCode(long lng) { return (int)(lng ^ lng >>> 32); } public static String identityToString(Object obj) { return obj == null?"":obj.getClass().getName() + "@" + getIdentityHexString(obj); } public static String getIdentityHexString(Object obj) { return Integer.toHexString(System.identityHashCode(obj)); } public static String getDisplayString(Object obj) { return obj == null?"":nullSafeToString(obj); } public static String nullSafeClassName(Object obj) { return obj != null?obj.getClass().getName():"null"; } public static String nullSafeToString(Object obj) { if(obj == null) { return "null"; } else if(obj instanceof String) { return (String)obj; } else if(obj instanceof Object[]) { return nullSafeToString((Object[])((Object[])obj)); } else if(obj instanceof boolean[]) { return nullSafeToString((boolean[])((boolean[])obj)); } else if(obj instanceof byte[]) { return nullSafeToString((byte[])((byte[])obj)); } else if(obj instanceof char[]) { return nullSafeToString((char[])((char[])obj)); } else if(obj instanceof double[]) { return nullSafeToString((double[])((double[])obj)); } else if(obj instanceof float[]) { return nullSafeToString((float[])((float[])obj)); } else if(obj instanceof int[]) { return nullSafeToString((int[])((int[])obj)); } else if(obj instanceof long[]) { return nullSafeToString((long[])((long[])obj)); } else if(obj instanceof short[]) { return nullSafeToString((short[])((short[])obj)); } else { String str = obj.toString(); return str != null?str:""; } } public static String nullSafeToString(Object[] array) { if(array == null) { return "null"; } else { int length = array.length; if(length == 0) { return "{}"; } else { StringBuilder sb = new StringBuilder("{"); for(int i = 0; i < length; ++i) { if(i > 0) { sb.append(", "); } sb.append(array[i]); } sb.append("}"); return sb.toString(); } } } public static String nullSafeToString(boolean[] array) { if(array == null) { return "null"; } else { int length = array.length; if(length == 0) { return "{}"; } else { StringBuilder sb = new StringBuilder("{"); for(int i = 0; i < length; ++i) { if(i > 0) { sb.append(", "); } sb.append(array[i]); } sb.append("}"); return sb.toString(); } } } public static String nullSafeToString(byte[] array) { if(array == null) { return "null"; } else { int length = array.length; if(length == 0) { return "{}"; } else { StringBuilder sb = new StringBuilder("{"); for(int i = 0; i < length; ++i) { if(i > 0) { sb.append(", "); } sb.append(array[i]); } sb.append("}"); return sb.toString(); } } } public static String nullSafeToString(char[] array) { if(array == null) { return "null"; } else { int length = array.length; if(length == 0) { return "{}"; } else { StringBuilder sb = new StringBuilder("{"); for(int i = 0; i < length; ++i) { if(i > 0) { sb.append(", "); } sb.append("\'").append(array[i]).append("\'"); } sb.append("}"); return sb.toString(); } } } public static String nullSafeToString(double[] array) { if(array == null) { return "null"; } else { int length = array.length; if(length == 0) { return "{}"; } else { StringBuilder sb = new StringBuilder("{"); for(int i = 0; i < length; ++i) { if(i > 0) { sb.append(", "); } sb.append(array[i]); } sb.append("}"); return sb.toString(); } } } public static String nullSafeToString(float[] array) { if(array == null) { return "null"; } else { int length = array.length; if(length == 0) { return "{}"; } else { StringBuilder sb = new StringBuilder("{"); for(int i = 0; i < length; ++i) { if(i > 0) { sb.append(", "); } sb.append(array[i]); } sb.append("}"); return sb.toString(); } } } public static String nullSafeToString(int[] array) { if(array == null) { return "null"; } else { int length = array.length; if(length == 0) { return "{}"; } else { StringBuilder sb = new StringBuilder("{"); for(int i = 0; i < length; ++i) { if(i > 0) { sb.append(", "); } sb.append(array[i]); } sb.append("}"); return sb.toString(); } } } public static String nullSafeToString(long[] array) { if(array == null) { return "null"; } else { int length = array.length; if(length == 0) { return "{}"; } else { StringBuilder sb = new StringBuilder("{"); for(int i = 0; i < length; ++i) { if(i > 0) { sb.append(", "); } sb.append(array[i]); } sb.append("}"); return sb.toString(); } } } public static String nullSafeToString(short[] array) { if(array == null) { return "null"; } else { int length = array.length; if(length == 0) { return "{}"; } else { StringBuilder sb = new StringBuilder("{"); for(int i = 0; i < length; ++i) { if(i > 0) { sb.append(", "); } sb.append(array[i]); } sb.append("}"); return sb.toString(); } } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/ArthasBanner.java
core/src/main/java/com/taobao/arthas/core/util/ArthasBanner.java
package com.taobao.arthas.core.util; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.taobao.arthas.common.PidUtils; import com.taobao.arthas.core.shell.ShellServerOptions; import com.taobao.text.Color; import com.taobao.text.Decoration; import com.taobao.text.ui.TableElement; import com.taobao.text.util.RenderUtil; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import static com.taobao.text.ui.Element.label; /** * @author beiwei30 on 16/11/2016. */ public class ArthasBanner { private static final String LOGO_LOCATION = "/com/taobao/arthas/core/res/logo.txt"; private static final String CREDIT_LOCATION = "/com/taobao/arthas/core/res/thanks.txt"; private static final String VERSION_LOCATION = "/com/taobao/arthas/core/res/version"; private static final String WIKI = "https://arthas.aliyun.com/doc"; private static final String TUTORIALS = "https://arthas.aliyun.com/doc/arthas-tutorials.html"; private static final String ARTHAS_LATEST_VERSIONS_URL = "https://arthas.aliyun.com/api/latest_version"; private static final int CONNECTION_TIMEOUT = 1000; private static final int READ_TIMEOUT = 1000; private static String LOGO = "Welcome to Arthas"; private static String VERSION = "unknown"; private static String THANKS = ""; private static final Logger logger = LoggerFactory.getLogger(ArthasBanner.class); static { try { String logoText = IOUtils.toString(ShellServerOptions.class.getResourceAsStream(LOGO_LOCATION)); THANKS = IOUtils.toString(ShellServerOptions.class.getResourceAsStream(CREDIT_LOCATION)); InputStream versionInputStream = ShellServerOptions.class.getResourceAsStream(VERSION_LOCATION); if (versionInputStream != null) { VERSION = IOUtils.toString(versionInputStream).trim(); } else { String implementationVersion = ArthasBanner.class.getPackage().getImplementationVersion(); if (implementationVersion != null) { VERSION = implementationVersion; } } StringBuilder sb = new StringBuilder(); String[] LOGOS = new String[6]; int i = 0, j = 0; for (String line : logoText.split("\n")) { sb.append(line); sb.append("\n"); if (i++ == 4) { LOGOS[j++] = sb.toString(); i = 0; sb.setLength(0); } } TableElement logoTable = new TableElement(); logoTable.row(label(LOGOS[0]).style(Decoration.bold.fg(Color.red)), label(LOGOS[1]).style(Decoration.bold.fg(Color.yellow)), label(LOGOS[2]).style(Decoration.bold.fg(Color.cyan)), label(LOGOS[3]).style(Decoration.bold.fg(Color.magenta)), label(LOGOS[4]).style(Decoration.bold.fg(Color.green)), label(LOGOS[5]).style(Decoration.bold.fg(Color.blue))); LOGO = RenderUtil.render(logoTable); } catch (Throwable e) { e.printStackTrace(); } } public static String wiki() { return WIKI; } public static String tutorials() { return TUTORIALS; } public static String credit() { return THANKS; } public static String version() { return VERSION; } public static String logo() { return LOGO; } public static String plainTextLogo() { return RenderUtil.ansiToPlainText(LOGO); } public static String welcome() { return welcome(Collections.<String, String>emptyMap()); } public static String welcome(Map<String, String> infos) { logger.info("Current arthas version: {}, recommend latest version: {}", version(), latestVersion()); String appName = System.getProperty("project.name"); if (appName == null) { appName = System.getProperty("app.name"); } if (appName == null) { appName = System.getProperty("spring.application.name"); } TableElement table = new TableElement().rightCellPadding(1) .row("wiki", wiki()) .row("tutorials", tutorials()) .row("version", version()) .row("main_class", PidUtils.mainClass()); if (appName != null) { table.row("app_name", appName); } table.row("pid", PidUtils.currentPid()) .row("start_time", DateUtils.getStartDateTime()) .row("current_time", DateUtils.getCurrentDateTime()); for (Entry<String, String> entry : infos.entrySet()) { table.row(entry.getKey(), entry.getValue()); } return logo() + "\n" + RenderUtil.render(table); } static String latestVersion() { final String[] version = { "" }; Thread thread = new Thread(new Runnable() { @Override public void run() { try { URLConnection urlConnection = openURLConnection(ARTHAS_LATEST_VERSIONS_URL); InputStream inputStream = urlConnection.getInputStream(); version[0] = com.taobao.arthas.common.IOUtils.toString(inputStream).trim(); } catch (Throwable e) { logger.debug("get latest version error", e); } } }); thread.setDaemon(true); thread.start(); try { thread.join(2000); // Wait up to 2 seconds for the version check } catch (Throwable e) { // Ignore } return version[0]; } /** * support redirect * * @param url * @return * @throws MalformedURLException * @throws IOException */ private static URLConnection openURLConnection(String url) throws MalformedURLException, IOException { URLConnection connection = new URL(url).openConnection(); if (connection instanceof HttpURLConnection) { connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); // normally, 3xx is redirect int status = ((HttpURLConnection) connection).getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) { String newUrl = connection.getHeaderField("Location"); logger.debug("Try to open url: {}, redirect to: {}", url, newUrl); return openURLConnection(newUrl); } } } return connection; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/ResultUtils.java
core/src/main/java/com/taobao/arthas/core/util/ResultUtils.java
package com.taobao.arthas.core.util; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * 命令结果处理工具类 * @author gongdewei 2020/5/18 */ public class ResultUtils { /** * 分页处理class列表,转换为className列表 * @param classes * @param pageSize * @param handler */ public static void processClassNames(Collection<Class<?>> classes, int pageSize, PaginationHandler<List<String>> handler) { List<String> classNames = new ArrayList<String>(pageSize); int segment = 0; for (Class aClass : classes) { classNames.add(aClass.getName()); //slice segment if(classNames.size() >= pageSize) { handler.handle(classNames, segment++); classNames = new ArrayList<String>(pageSize); } } //last segment if (classNames.size() > 0) { handler.handle(classNames, segment++); } } /** * 分页数据处理回调接口 * @param <T> */ public interface PaginationHandler<T> { /** * 处理分页数据 * @param list * @param segment * @return true 继续处理剩余数据, false 终止处理 */ boolean handle(T list, int segment); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/StringUtils.java
core/src/main/java/com/taobao/arthas/core/util/StringUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.util; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Modifier; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.concurrent.ThreadLocalRandom; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; public abstract class StringUtils { private static final Logger logger = LoggerFactory.getLogger(StringUtils.class); private static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; /** * 获取异常的原因描述 * * @param t 异常 * @return 异常原因 */ public static String cause(Throwable t) { if (null != t.getCause()) { return cause(t.getCause()); } return t.getMessage(); } /** * 将一个对象转换为字符串 * * @param obj 目标对象 * @return 字符串 */ public static String objectToString(Object obj) { if (null == obj) { return Constants.EMPTY_STRING; } try { return obj.toString(); } catch (Throwable t) { logger.error("objectToString error, obj class: {}", obj.getClass(), t); return "ERROR DATA!!! Method toString() throw exception. obj class: " + obj.getClass() + ", exception class: " + t.getClass() + ", exception message: " + t.getMessage(); } } /** * 翻译类名称 * * @param clazz Java类 * @return 翻译值 */ public static String classname(Class<?> clazz) { if (clazz.isArray()) { StringBuilder sb = new StringBuilder(clazz.getName()); sb.delete(0, 2); if (sb.length() > 0 && sb.charAt(sb.length() - 1) == ';') { sb.deleteCharAt(sb.length() - 1); } sb.append("[]"); return sb.toString(); } else { return clazz.getName(); } } /** * 翻译类名称<br/> * 将 java/lang/String 的名称翻译成 java.lang.String * * @param className 类名称 java/lang/String * @return 翻译后名称 java.lang.String */ public static String normalizeClassName(String className) { return StringUtils.replace(className, "/", "."); } public static String concat(String separator, Class<?>... types) { if (types == null || types.length == 0) { return Constants.EMPTY_STRING; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < types.length; i++) { builder.append(classname(types[i])); if (i < types.length - 1) { builder.append(separator); } } return builder.toString(); } public static String concat(String separator, String... strs) { if (strs == null || strs.length == 0) { return Constants.EMPTY_STRING; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < strs.length; i++) { builder.append(strs[i]); if (i < strs.length - 1) { builder.append(separator); } } return builder.toString(); } /** * 翻译Modifier值 * * @param mod modifier * @return 翻译值 */ public static String modifier(int mod, char splitter) { StringBuilder sb = new StringBuilder(); if (Modifier.isAbstract(mod)) { sb.append("abstract").append(splitter); } if (Modifier.isFinal(mod)) { sb.append("final").append(splitter); } if (Modifier.isInterface(mod)) { sb.append("interface").append(splitter); } if (Modifier.isNative(mod)) { sb.append("native").append(splitter); } if (Modifier.isPrivate(mod)) { sb.append("private").append(splitter); } if (Modifier.isProtected(mod)) { sb.append("protected").append(splitter); } if (Modifier.isPublic(mod)) { sb.append("public").append(splitter); } if (Modifier.isStatic(mod)) { sb.append("static").append(splitter); } if (Modifier.isStrict(mod)) { sb.append("strict").append(splitter); } if (Modifier.isSynchronized(mod)) { sb.append("synchronized").append(splitter); } if (Modifier.isTransient(mod)) { sb.append("transient").append(splitter); } if (Modifier.isVolatile(mod)) { sb.append("volatile").append(splitter); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } /** * 自动换行 * * @param string 字符串 * @param width 行宽 * @return 换行后的字符串 */ public static String wrap(String string, int width) { final StringBuilder sb = new StringBuilder(); final char[] buffer = string.toCharArray(); int count = 0; for (char c : buffer) { if (count == width) { count = 0; sb.append('\n'); if (c == '\n') { continue; } } if (c == '\n') { count = 0; } else { count++; } sb.append(c); } return sb.toString(); } /** * <p>The maximum size to which the padding constant(s) can expand.</p> */ private static final int PAD_LIMIT = 8192; /** * Represents a failed index search. * @since 2.1 */ public static final int INDEX_NOT_FOUND = -1; public StringUtils() { } public static boolean isEmpty(Object str) { return str == null || "".equals(str); } public static boolean hasLength(CharSequence str) { return str != null && str.length() > 0; } public static boolean hasLength(String str) { return hasLength((CharSequence)str); } public static boolean hasText(CharSequence str) { if(!hasLength(str)) { return false; } else { int strLen = str.length(); for(int i = 0; i < strLen; ++i) { if(!Character.isWhitespace(str.charAt(i))) { return true; } } return false; } } public static boolean hasText(String str) { return hasText((CharSequence)str); } public static boolean containsWhitespace(CharSequence str) { if(!hasLength(str)) { return false; } else { int strLen = str.length(); for(int i = 0; i < strLen; ++i) { if(Character.isWhitespace(str.charAt(i))) { return true; } } return false; } } public static boolean containsWhitespace(String str) { return containsWhitespace((CharSequence)str); } public static String trimWhitespace(String str) { if(!hasLength(str)) { return str; } else { StringBuilder sb = new StringBuilder(str); while(sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) { sb.deleteCharAt(0); } while(sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } } public static String trimAllWhitespace(String str) { if(!hasLength(str)) { return str; } else { StringBuilder sb = new StringBuilder(str); int index = 0; while(sb.length() > index) { if(Character.isWhitespace(sb.charAt(index))) { sb.deleteCharAt(index); } else { ++index; } } return sb.toString(); } } public static String trimLeadingWhitespace(String str) { if(!hasLength(str)) { return str; } else { StringBuilder sb = new StringBuilder(str); while(sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) { sb.deleteCharAt(0); } return sb.toString(); } } public static String trimTrailingWhitespace(String str) { if(!hasLength(str)) { return str; } else { StringBuilder sb = new StringBuilder(str); while(sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } } public static String trimLeadingCharacter(String str, char leadingCharacter) { if(!hasLength(str)) { return str; } else { StringBuilder sb = new StringBuilder(str); while(sb.length() > 0 && sb.charAt(0) == leadingCharacter) { sb.deleteCharAt(0); } return sb.toString(); } } public static String trimTrailingCharacter(String str, char trailingCharacter) { if(!hasLength(str)) { return str; } else { StringBuilder sb = new StringBuilder(str); while(sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } } public static boolean startsWithIgnoreCase(String str, String prefix) { if(str != null && prefix != null) { if(str.startsWith(prefix)) { return true; } else if(str.length() < prefix.length()) { return false; } else { String lcStr = str.substring(0, prefix.length()).toLowerCase(); String lcPrefix = prefix.toLowerCase(); return lcStr.equals(lcPrefix); } } else { return false; } } public static boolean endsWithIgnoreCase(String str, String suffix) { if(str != null && suffix != null) { if(str.endsWith(suffix)) { return true; } else if(str.length() < suffix.length()) { return false; } else { String lcStr = str.substring(str.length() - suffix.length()).toLowerCase(); String lcSuffix = suffix.toLowerCase(); return lcStr.equals(lcSuffix); } } else { return false; } } public static boolean substringMatch(CharSequence str, int index, CharSequence substring) { for(int j = 0; j < substring.length(); ++j) { int i = index + j; if(i >= str.length() || str.charAt(i) != substring.charAt(j)) { return false; } } return true; } public static String substringAfter(String str, String separator) { if (isEmpty(str)) { return str; } else if (separator == null) { return ""; } else { int pos = str.indexOf(separator); return pos == -1 ? "" : str.substring(pos + separator.length()); } } public static String substringBeforeLast(String str, String separator) { if (!isEmpty(str) && !isEmpty(separator)) { int pos = str.lastIndexOf(separator); return pos == -1 ? str : str.substring(0, pos); } else { return str; } } public static String substringBefore(final String str, final String separator) { if (isEmpty(str) || separator == null) { return str; } if (separator.isEmpty()) { return Constants.EMPTY_STRING; } final int pos = str.indexOf(separator); if (pos == -1) { return str; } return str.substring(0, pos); } public static String substringAfterLast(String str, String separator) { if (isEmpty(str)) { return str; } else if (isEmpty(separator)) { return ""; } else { int pos = str.lastIndexOf(separator); return pos != -1 && pos != str.length() - separator.length() ? str.substring(pos + separator.length()) : ""; } } public static int countOccurrencesOf(String str, String sub) { if(str != null && sub != null && str.length() != 0 && sub.length() != 0) { int count = 0; int idx; for(int pos = 0; (idx = str.indexOf(sub, pos)) != -1; pos = idx + sub.length()) { ++count; } return count; } else { return 0; } } public static String replace(String inString, String oldPattern, String newPattern) { if(hasLength(inString) && hasLength(oldPattern) && newPattern != null) { int pos = 0; int index = inString.indexOf(oldPattern); if (index < 0) { //no need to replace return inString; } StringBuilder sb = new StringBuilder(); for(int patLen = oldPattern.length(); index >= 0; index = inString.indexOf(oldPattern, pos)) { sb.append(inString, pos, index); sb.append(newPattern); pos = index + patLen; } sb.append(inString.substring(pos)); return sb.toString(); } else { return inString; } } public static String delete(String inString, String pattern) { return replace(inString, pattern, ""); } public static String deleteAny(String inString, String charsToDelete) { if(hasLength(inString) && hasLength(charsToDelete)) { StringBuilder sb = new StringBuilder(); for(int i = 0; i < inString.length(); ++i) { char c = inString.charAt(i); if(charsToDelete.indexOf(c) == -1) { sb.append(c); } } return sb.toString(); } else { return inString; } } public static String quote(String str) { return str != null?"\'" + str + "\'":null; } public static Object quoteIfString(Object obj) { return obj instanceof String?quote((String)obj):obj; } public static String unqualify(String qualifiedName) { return unqualify(qualifiedName, '.'); } public static String unqualify(String qualifiedName, char separator) { return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1); } public static String capitalize(String str) { return changeFirstCharacterCase(str, true); } public static String uncapitalize(String str) { return changeFirstCharacterCase(str, false); } private static String changeFirstCharacterCase(String str, boolean capitalize) { if(str != null && str.length() != 0) { StringBuilder sb = new StringBuilder(str.length()); if(capitalize) { sb.append(Character.toUpperCase(str.charAt(0))); } else { sb.append(Character.toLowerCase(str.charAt(0))); } sb.append(str.substring(1)); return sb.toString(); } else { return str; } } public static String[] toStringArray(Collection<String> collection) { return collection == null?null:(String[])collection.toArray(new String[0]); } public static String[] split(String toSplit, String delimiter) { if(hasLength(toSplit) && hasLength(delimiter)) { int offset = toSplit.indexOf(delimiter); if(offset < 0) { return null; } else { String beforeDelimiter = toSplit.substring(0, offset); String afterDelimiter = toSplit.substring(offset + delimiter.length()); return new String[]{beforeDelimiter, afterDelimiter}; } } else { return null; } } public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) { return splitArrayElementsIntoProperties(array, delimiter, (String)null); } public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter, String charsToDelete) { if(ObjectUtils.isEmpty(array)) { return null; } else { Properties result = new Properties(); String[] var4 = array; int var5 = array.length; for(int var6 = 0; var6 < var5; ++var6) { String element = var4[var6]; if(charsToDelete != null) { element = deleteAny(element, charsToDelete); } String[] splittedElement = split(element, delimiter); if(splittedElement != null) { result.setProperty(splittedElement[0].trim(), splittedElement[1].trim()); } } return result; } } public static String[] tokenizeToStringArray(String str, String delimiters) { return tokenizeToStringArray(str, delimiters, true, true); } public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { if(str == null) { return null; } else { StringTokenizer st = new StringTokenizer(str, delimiters); ArrayList<String> tokens = new ArrayList<String>(); while(true) { String token; do { if(!st.hasMoreTokens()) { return toStringArray(tokens); } token = st.nextToken(); if(trimTokens) { token = token.trim(); } } while(ignoreEmptyTokens && token.length() <= 0); tokens.add(token); } } } public static String[] delimitedListToStringArray(String str, String delimiter) { return delimitedListToStringArray(str, delimiter, (String)null); } public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) { if(str == null) { return new String[0]; } else if(delimiter == null) { return new String[]{str}; } else { ArrayList<String> result = new ArrayList<String>(); int pos; if("".equals(delimiter)) { for(pos = 0; pos < str.length(); ++pos) { result.add(deleteAny(str.substring(pos, pos + 1), charsToDelete)); } } else { int delPos; for(pos = 0; (delPos = str.indexOf(delimiter, pos)) != -1; pos = delPos + delimiter.length()) { result.add(deleteAny(str.substring(pos, delPos), charsToDelete)); } if(str.length() > 0 && pos <= str.length()) { result.add(deleteAny(str.substring(pos), charsToDelete)); } } return toStringArray(result); } } public static String[] commaDelimitedListToStringArray(String str) { return delimitedListToStringArray(str, ","); } public static Set<String> commaDelimitedListToSet(String str) { String[] tokens = commaDelimitedListToStringArray(str); return new TreeSet<String>(Arrays.asList(tokens)); } /** * <p> * Joins the elements of the provided array into a single String containing the provided list of * elements. * </p> * * <p> * No delimiter is added before or after the list. A <code>null</code> separator is the same as a * blank String. * </p> * * @param array the array of values to join together * @param separator the separator character to use * @return the joined String */ public static String join(Object[] array, String separator) { if (separator == null) { separator = ""; } int arraySize = array.length; int bufSize = (arraySize == 0 ? 0 : (array[0].toString().length() + separator.length()) * arraySize); StringBuilder buf = new StringBuilder(bufSize); for (int i = 0; i < arraySize; i++) { if (i > 0) { buf.append(separator); } buf.append(array[i]); } return buf.toString(); } /** * <p>Checks if a CharSequence is whitespace, empty ("") or null.</p> * * <pre> * StringUtils.isBlank(null) = true * StringUtils.isBlank("") = true * StringUtils.isBlank(" ") = true * StringUtils.isBlank("bob") = false * StringUtils.isBlank(" bob ") = false * </pre> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is null, empty or whitespace * @since 2.0 * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence) */ public static boolean isBlank(final CharSequence cs) { int strLen; if (cs == null || (strLen = cs.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } } return true; } /** * <p>Returns padding using the specified delimiter repeated * to a given length.</p> * * <pre> * StringUtils.repeat('e', 0) = "" * StringUtils.repeat('e', 3) = "eee" * StringUtils.repeat('e', -2) = "" * </pre> * * <p>Note: this method doesn't not support padding with * <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a> * as they require a pair of {@code char}s to be represented. * If you are needing to support full I18N of your applications * consider using {@link #repeat(String, int)} instead. * </p> * * @param ch character to repeat * @param repeat number of times to repeat char, negative treated as zero * @return String with repeated character * @see #repeat(String, int) */ public static String repeat(final char ch, final int repeat) { final char[] buf = new char[repeat]; for (int i = repeat - 1; i >= 0; i--) { buf[i] = ch; } return new String(buf); } /** * <p>Repeat a String {@code repeat} times to form a * new String.</p> * * <pre> * StringUtils.repeat(null, 2) = null * StringUtils.repeat("", 0) = "" * StringUtils.repeat("", 2) = "" * StringUtils.repeat("a", 3) = "aaa" * StringUtils.repeat("ab", 2) = "abab" * StringUtils.repeat("a", -2) = "" * </pre> * * @param str the String to repeat, may be null * @param repeat number of times to repeat str, negative treated as zero * @return a new String consisting of the original String repeated, * {@code null} if null String input */ public static String repeat(final String str, final int repeat) { // Performance tuned for 2.0 (JDK1.4) if (str == null) { return null; } if (repeat <= 0) { return Constants.EMPTY_STRING; } final int inputLength = str.length(); if (repeat == 1 || inputLength == 0) { return str; } if (inputLength == 1 && repeat <= PAD_LIMIT) { return repeat(str.charAt(0), repeat); } final int outputLength = inputLength * repeat; switch (inputLength) { case 1 : return repeat(str.charAt(0), repeat); case 2 : final char ch0 = str.charAt(0); final char ch1 = str.charAt(1); final char[] output2 = new char[outputLength]; for (int i = repeat * 2 - 2; i >= 0; i--, i--) { output2[i] = ch0; output2[i + 1] = ch1; } return new String(output2); default : final StringBuilder buf = new StringBuilder(outputLength); for (int i = 0; i < repeat; i++) { buf.append(str); } return buf.toString(); } } /** * Gets a CharSequence length or {@code 0} if the CharSequence is * {@code null}. * * @param cs * a CharSequence or {@code null} * @return CharSequence length or {@code 0} if the CharSequence is * {@code null}. * @since 2.4 * @since 3.0 Changed signature from length(String) to length(CharSequence) */ public static int length(final CharSequence cs) { return cs == null ? 0 : cs.length(); } /** * <p>Strips any of a set of characters from the end of a String.</p> * * <p>A {@code null} input String returns {@code null}. * An empty string ("") input returns the empty string.</p> * * <p>If the stripChars String is {@code null}, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.stripEnd(null, *) = null * StringUtils.stripEnd("", *) = "" * StringUtils.stripEnd("abc", "") = "abc" * StringUtils.stripEnd("abc", null) = "abc" * StringUtils.stripEnd(" abc", null) = " abc" * StringUtils.stripEnd("abc ", null) = "abc" * StringUtils.stripEnd(" abc ", null) = " abc" * StringUtils.stripEnd(" abcyx", "xyz") = " abc" * StringUtils.stripEnd("120.00", ".0") = "12" * </pre> * * @param str the String to remove characters from, may be null * @param stripChars the set of characters to remove, null treated as whitespace * @return the stripped String, {@code null} if null String input */ public static String stripEnd(final String str, final String stripChars) { int end; if (str == null || (end = str.length()) == 0) { return str; } if (stripChars == null) { while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) { end--; } } else if (stripChars.isEmpty()) { return str; } else { while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND) { end--; } } return str.substring(0, end); } public static String classLoaderHash(Class<?> clazz) { if (clazz == null || clazz.getClassLoader() == null) { return "null"; } return Integer.toHexString(clazz.getClassLoader().hashCode()); } /** * format byte size to human readable format. https://stackoverflow.com/a/3758880 * @param bytes byets * @return human readable format */ public static String humanReadableByteCount(long bytes) { return bytes < 1024L ? bytes + " B" : bytes < 0xfffccccccccccccL >> 40 ? String.format("%.1f KiB", bytes / 0x1p10) : bytes < 0xfffccccccccccccL >> 30 ? String.format("%.1f MiB", bytes / 0x1p20) : bytes < 0xfffccccccccccccL >> 20 ? String.format("%.1f GiB", bytes / 0x1p30) : bytes < 0xfffccccccccccccL >> 10 ? String.format("%.1f TiB", bytes / 0x1p40) : bytes < 0xfffccccccccccccL ? String.format("%.1f PiB", (bytes >> 10) / 0x1p40) : String.format("%.1f EiB", (bytes >> 20) / 0x1p40); } public static List<String> toLines(String text) { List<String> result = new ArrayList<String>(); BufferedReader reader = new BufferedReader(new StringReader(text)); try { String line = reader.readLine(); while (line != null) { result.add(line); line = reader.readLine(); } } catch (IOException exc) { // quit } finally { try { reader.close(); } catch (IOException e) { // ignore } } return result; } public static String randomString(int length) { StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) sb.append(AB.charAt(ThreadLocalRandom.current().nextInt(AB.length()))); return sb.toString(); } /** * Returns the string before the given token * * @param text the text * @param before the token * @return the text before the token, or <tt>null</tt> if text does not contain * the token */ public static String before(String text, String before) { int pos = text.indexOf(before); return pos == -1 ? null : text.substring(0, pos); } /** * Returns the string after the given token * * @param text the text * @param after the token * @return the text after the token, or <tt>null</tt> if text does not contain * the token */ public static String after(String text, String after) { int pos = text.indexOf(after); if (pos == -1) { return null; } return text.substring(pos + after.length()); } // print|(ILjava/util/List;)V public static String[] splitMethodInfo(String methodInfo) { int index = methodInfo.indexOf('|'); return new String[] { methodInfo.substring(0, index), methodInfo.substring(index + 1) }; } // demo/MathGame|primeFactors|(I)Ljava/util/List;|24 public static String[] splitInvokeInfo(String invokeInfo) { int index1 = invokeInfo.indexOf('|'); int index2 = invokeInfo.indexOf('|', index1 + 1); int index3 = invokeInfo.indexOf('|', index2 + 1); return new String[] { invokeInfo.substring(0, index1), invokeInfo.substring(index1 + 1, index2), invokeInfo.substring(index2 + 1, index3), invokeInfo.substring(index3 + 1) }; } public static String beautifyName(String name) { return name.replace(' ', '_').toLowerCase(); } public static List<String> toStringList(URL[] urls) { if (urls != null) { List<String> result = new ArrayList<String>(urls.length); for (URL url : urls) { result.add(url.toString()); } return result; } return Collections.emptyList(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/TypeRenderUtils.java
core/src/main/java/com/taobao/arthas/core/util/TypeRenderUtils.java
package com.taobao.arthas.core.util; import com.taobao.arthas.core.command.model.ClassDetailVO; import com.taobao.arthas.core.command.model.ClassVO; import com.taobao.arthas.core.command.model.FieldVO; import com.taobao.arthas.core.command.model.ObjectVO; import com.taobao.arthas.core.view.ObjectView; import com.taobao.text.ui.Element; import com.taobao.text.ui.TableElement; import com.taobao.text.ui.TreeElement; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import static com.taobao.text.ui.Element.label; /** * @author beiwei30 on 24/11/2016. */ public class TypeRenderUtils { public static String drawInterface(Class<?> clazz) { return StringUtils.concat(",", clazz.getInterfaces()); } public static String drawParameters(Method method) { return StringUtils.concat("\n", method.getParameterTypes()); } public static String drawParameters(Constructor constructor) { return StringUtils.concat("\n", constructor.getParameterTypes()); } public static String drawParameters(String[] parameterTypes) { return StringUtils.concat("\n", parameterTypes); } public static String drawReturn(Method method) { return StringUtils.classname(method.getReturnType()); } public static String drawExceptions(Method method) { return StringUtils.concat("\n", method.getExceptionTypes()); } public static String drawExceptions(Constructor constructor) { return StringUtils.concat("\n", constructor.getExceptionTypes()); } public static String drawExceptions(String[] exceptionTypes) { return StringUtils.concat("\n", exceptionTypes); } public static Element drawSuperClass(ClassDetailVO clazz) { return drawTree(clazz.getSuperClass()); } public static Element drawClassLoader(ClassVO clazz) { String[] classloaders = clazz.getClassloader(); return drawTree(classloaders); } public static Element drawTree(String[] nodes) { TreeElement root = new TreeElement(); TreeElement parent = root; for (String node : nodes) { TreeElement child = new TreeElement(label(node)); parent.addChild(child); parent = child; } return root; } public static Element drawField(ClassDetailVO clazz) { TableElement fieldsTable = new TableElement(1).leftCellPadding(0).rightCellPadding(0); FieldVO[] fields = clazz.getFields(); if (fields == null || fields.length == 0) { return fieldsTable; } for (FieldVO field : fields) { TableElement fieldTable = new TableElement().leftCellPadding(0).rightCellPadding(1); fieldTable.row("name", field.getName()) .row("type", field.getType()) .row("modifier", field.getModifier()); String[] annotations = field.getAnnotations(); if (annotations != null && annotations.length > 0) { fieldTable.row("annotation", drawAnnotation(annotations)); } if (field.isStatic()) { ObjectVO objectVO = field.getValue(); Object o = objectVO.needExpand() ? new ObjectView(objectVO).draw() : objectVO.getObject(); fieldTable.row("value", StringUtils.objectToString(o)); } fieldTable.row(label("")); fieldsTable.row(fieldTable); } return fieldsTable; } public static String drawAnnotation(String... annotations) { return StringUtils.concat(",", annotations); } public static String[] getAnnotations(Class<?> clazz) { return getAnnotations(clazz.getDeclaredAnnotations()); } public static String[] getAnnotations(Annotation[] annotations) { List<String> list = new ArrayList<String>(); if (annotations != null && annotations.length > 0) { for (Annotation annotation : annotations) { list.add(StringUtils.classname(annotation.annotationType())); } } return list.toArray(new String[0]); } public static String[] getInterfaces(Class clazz) { Class[] interfaces = clazz.getInterfaces(); return ClassUtils.getClassNameList(interfaces); } public static String[] getSuperClass(Class clazz) { List<String> list = new ArrayList<String>(); Class<?> superClass = clazz.getSuperclass(); if (null != superClass) { list.add(StringUtils.classname(superClass)); while (true) { superClass = superClass.getSuperclass(); if (null == superClass) { break; } list.add(StringUtils.classname(superClass)); } } return list.toArray(new String[0]); } public static String[] getClassloader(Class clazz) { List<String> list = new ArrayList<String>(); ClassLoader loader = clazz.getClassLoader(); if (null != loader) { list.add(loader.toString()); while (true) { loader = loader.getParent(); if (null == loader) { break; } list.add(loader.toString()); } } return list.toArray(new String[0]); } public static FieldVO[] getFields(Class clazz, Integer expand) { Field[] fields = clazz.getDeclaredFields(); if (fields.length == 0) { return new FieldVO[0]; } List<FieldVO> list = new ArrayList<FieldVO>(fields.length); for (Field field : fields) { FieldVO fieldVO = new FieldVO(); fieldVO.setName(field.getName()); fieldVO.setType(StringUtils.classname(field.getType())); fieldVO.setModifier(StringUtils.modifier(field.getModifiers(), ',')); fieldVO.setAnnotations(getAnnotations(field.getAnnotations())); if (Modifier.isStatic(field.getModifiers())) { fieldVO.setStatic(true); fieldVO.setValue(new ObjectVO(getFieldValue(field), expand)); } else { fieldVO.setStatic(false); } list.add(fieldVO); } return list.toArray(new FieldVO[0]); } private static Object getFieldValue(Field field) { final boolean isAccessible = field.isAccessible(); try { field.setAccessible(true); Object value = field.get(null); return value; } catch (IllegalAccessException e) { // no op } finally { field.setAccessible(isAccessible); } return null; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/ClassUtils.java
core/src/main/java/com/taobao/arthas/core/util/ClassUtils.java
package com.taobao.arthas.core.util; import static com.taobao.text.ui.Element.label; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.security.CodeSource; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.alibaba.deps.org.objectweb.asm.Type; import com.taobao.arthas.core.command.model.ClassDetailVO; import com.taobao.arthas.core.command.model.ClassLoaderVO; import com.taobao.arthas.core.command.model.ClassVO; import com.taobao.arthas.core.command.model.MethodVO; import com.taobao.text.Color; import com.taobao.text.Decoration; import com.taobao.text.ui.Element; import com.taobao.text.ui.LabelElement; import com.taobao.text.ui.TableElement; import static com.taobao.text.Decoration.bold; /** * * @author hengyunabc 2018-10-18 * */ public class ClassUtils { public static String getCodeSource(final CodeSource cs) { if (null == cs || null == cs.getLocation() || null == cs.getLocation().getFile()) { return com.taobao.arthas.core.util.Constants.EMPTY_STRING; } return cs.getLocation().getFile(); } public static boolean isLambdaClass(Class<?> clazz) { return clazz.getName().contains("$$Lambda"); } public static Element renderClassInfo(ClassDetailVO clazz) { return renderClassInfo(clazz, false); } public static Element renderClassInfo(ClassDetailVO clazz, boolean isPrintField) { TableElement table = new TableElement().leftCellPadding(1).rightCellPadding(1); table.row(label("class-info").style(Decoration.bold.bold()), label(clazz.getClassInfo())) .row(label("code-source").style(Decoration.bold.bold()), label(clazz.getCodeSource())) .row(label("name").style(Decoration.bold.bold()), label(clazz.getName())) .row(label("isInterface").style(Decoration.bold.bold()), label("" + clazz.isInterface())) .row(label("isAnnotation").style(Decoration.bold.bold()), label("" + clazz.isAnnotation())) .row(label("isEnum").style(Decoration.bold.bold()), label("" + clazz.isEnum())) .row(label("isAnonymousClass").style(Decoration.bold.bold()), label("" + clazz.isAnonymousClass())) .row(label("isArray").style(Decoration.bold.bold()), label("" + clazz.isArray())) .row(label("isLocalClass").style(Decoration.bold.bold()), label("" + clazz.isLocalClass())) .row(label("isMemberClass").style(Decoration.bold.bold()), label("" + clazz.isMemberClass())) .row(label("isPrimitive").style(Decoration.bold.bold()), label("" + clazz.isPrimitive())) .row(label("isSynthetic").style(Decoration.bold.bold()), label("" + clazz.isSynthetic())) .row(label("simple-name").style(Decoration.bold.bold()), label(clazz.getSimpleName())) .row(label("modifier").style(Decoration.bold.bold()), label(clazz.getModifier())) .row(label("annotation").style(Decoration.bold.bold()), label(StringUtils.join(clazz.getAnnotations(), ","))) .row(label("interfaces").style(Decoration.bold.bold()), label(StringUtils.join(clazz.getInterfaces(), ","))) .row(label("super-class").style(Decoration.bold.bold()), TypeRenderUtils.drawSuperClass(clazz)) .row(label("class-loader").style(Decoration.bold.bold()), TypeRenderUtils.drawClassLoader(clazz)) .row(label("classLoaderHash").style(Decoration.bold.bold()), label(clazz.getClassLoaderHash())); if (isPrintField) { table.row(label("fields").style(Decoration.bold.bold()), TypeRenderUtils.drawField(clazz)); } return table; } public static ClassDetailVO createClassInfo(Class clazz, boolean withFields, Integer expand) { CodeSource cs = clazz.getProtectionDomain().getCodeSource(); ClassDetailVO classInfo = new ClassDetailVO(); classInfo.setName(StringUtils.classname(clazz)); classInfo.setClassInfo(StringUtils.classname(clazz)); classInfo.setCodeSource(ClassUtils.getCodeSource(cs)); classInfo.setInterface(clazz.isInterface()); classInfo.setAnnotation(clazz.isAnnotation()); classInfo.setEnum(clazz.isEnum()); classInfo.setAnonymousClass(clazz.isAnonymousClass()); classInfo.setArray(clazz.isArray()); classInfo.setLocalClass(clazz.isLocalClass()); classInfo.setMemberClass(clazz.isMemberClass()); classInfo.setPrimitive(clazz.isPrimitive()); classInfo.setSynthetic(clazz.isSynthetic()); classInfo.setSimpleName(clazz.getSimpleName()); classInfo.setModifier(StringUtils.modifier(clazz.getModifiers(), ',')); classInfo.setAnnotations(TypeRenderUtils.getAnnotations(clazz)); classInfo.setInterfaces(TypeRenderUtils.getInterfaces(clazz)); classInfo.setSuperClass(TypeRenderUtils.getSuperClass(clazz)); classInfo.setClassloader(TypeRenderUtils.getClassloader(clazz)); classInfo.setClassLoaderHash(StringUtils.classLoaderHash(clazz)); if (withFields) { classInfo.setFields(TypeRenderUtils.getFields(clazz, expand)); } return classInfo; } public static ClassVO createSimpleClassInfo(Class clazz) { ClassVO classInfo = new ClassVO(); fillSimpleClassVO(clazz, classInfo); return classInfo; } public static void fillSimpleClassVO(Class clazz, ClassVO classInfo) { classInfo.setName(StringUtils.classname(clazz)); classInfo.setClassloader(TypeRenderUtils.getClassloader(clazz)); classInfo.setClassLoaderHash(StringUtils.classLoaderHash(clazz)); } public static MethodVO createMethodInfo(Method method, Class clazz, boolean detail) { MethodVO methodVO = new MethodVO(); methodVO.setDeclaringClass(clazz.getName()); methodVO.setMethodName(method.getName()); methodVO.setDescriptor(Type.getMethodDescriptor(method)); methodVO.setConstructor(false); if (detail) { methodVO.setModifier(StringUtils.modifier(method.getModifiers(), ',')); methodVO.setAnnotations(TypeRenderUtils.getAnnotations(method.getDeclaredAnnotations())); methodVO.setParameters(getClassNameList(method.getParameterTypes())); methodVO.setReturnType(StringUtils.classname(method.getReturnType())); methodVO.setExceptions(getClassNameList(method.getExceptionTypes())); methodVO.setClassLoaderHash(StringUtils.classLoaderHash(clazz)); } return methodVO; } public static MethodVO createMethodInfo(Constructor constructor, Class clazz, boolean detail) { MethodVO methodVO = new MethodVO(); methodVO.setDeclaringClass(clazz.getName()); methodVO.setDescriptor(Type.getConstructorDescriptor(constructor)); methodVO.setMethodName("<init>"); methodVO.setConstructor(true); if (detail) { methodVO.setModifier(StringUtils.modifier(constructor.getModifiers(), ',')); methodVO.setAnnotations(TypeRenderUtils.getAnnotations(constructor.getDeclaredAnnotations())); methodVO.setParameters(getClassNameList(constructor.getParameterTypes())); methodVO.setExceptions(getClassNameList(constructor.getExceptionTypes())); methodVO.setClassLoaderHash(StringUtils.classLoaderHash(clazz)); } return methodVO; } public static Element renderMethod(MethodVO method) { TableElement table = new TableElement().leftCellPadding(1).rightCellPadding(1); table.row(label("declaring-class").style(bold.bold()), label(method.getDeclaringClass())) .row(label("method-name").style(bold.bold()), label(method.getMethodName()).style(bold.bold())) .row(label("modifier").style(bold.bold()), label(method.getModifier())) .row(label("annotation").style(bold.bold()), label(TypeRenderUtils.drawAnnotation(method.getAnnotations()))) .row(label("parameters").style(bold.bold()), label(TypeRenderUtils.drawParameters(method.getParameters()))) .row(label("return").style(bold.bold()), label(method.getReturnType())) .row(label("exceptions").style(bold.bold()), label(TypeRenderUtils.drawExceptions(method.getExceptions()))) .row(label("classLoaderHash").style(bold.bold()), label(method.getClassLoaderHash())); return table; } public static Element renderConstructor(MethodVO constructor) { TableElement table = new TableElement().leftCellPadding(1).rightCellPadding(1); table.row(label("declaring-class").style(bold.bold()), label(constructor.getDeclaringClass())) .row(label("constructor-name").style(bold.bold()), label("<init>").style(bold.bold())) .row(label("modifier").style(bold.bold()), label(constructor.getModifier())) .row(label("annotation").style(bold.bold()), label(TypeRenderUtils.drawAnnotation(constructor.getAnnotations()))) .row(label("parameters").style(bold.bold()), label(TypeRenderUtils.drawParameters(constructor.getParameters()))) .row(label("exceptions").style(bold.bold()), label(TypeRenderUtils.drawExceptions(constructor.getExceptions()))) .row(label("classLoaderHash").style(bold.bold()), label(constructor.getClassLoaderHash())); return table; } public static String[] getClassNameList(Class[] classes) { List<String> list = new ArrayList<String>(); for (Class anInterface : classes) { list.add(StringUtils.classname(anInterface)); } return list.toArray(new String[0]); } public static List<ClassVO> createClassVOList(Collection<Class<?>> matchedClasses) { List<ClassVO> classVOs = new ArrayList<ClassVO>(matchedClasses.size()); for (Class<?> aClass : matchedClasses) { ClassVO classVO = createSimpleClassInfo(aClass); classVOs.add(classVO); } return classVOs; } public static ClassLoaderVO createClassLoaderVO(ClassLoader classLoader) { ClassLoaderVO classLoaderVO = new ClassLoaderVO(); classLoaderVO.setHash(classLoaderHash(classLoader)); classLoaderVO.setName(classLoader==null?"BootstrapClassLoader":classLoader.toString()); ClassLoader parent = classLoader == null ? null : classLoader.getParent(); classLoaderVO.setParent(parent==null?null:parent.toString()); return classLoaderVO; } public static List<ClassLoaderVO> createClassLoaderVOList(Collection<ClassLoader> classLoaders) { List<ClassLoaderVO> classLoaderVOList = new ArrayList<ClassLoaderVO>(); for (ClassLoader classLoader : classLoaders) { classLoaderVOList.add(createClassLoaderVO(classLoader)); } return classLoaderVOList; } public static String classLoaderHash(Class<?> clazz) { if (clazz == null || clazz.getClassLoader() == null) { return "null"; } return Integer.toHexString(clazz.getClassLoader().hashCode()); } public static String classLoaderHash(ClassLoader classLoader) { if (classLoader == null ) { return "null"; } return Integer.toHexString(classLoader.hashCode()); } public static Element renderMatchedClasses(Collection<ClassVO> matchedClasses) { TableElement table = new TableElement().leftCellPadding(1).rightCellPadding(1); table.row(new LabelElement("NAME").style(Decoration.bold.bold()), new LabelElement("HASHCODE").style(Decoration.bold.bold()), new LabelElement("CLASSLOADER").style(Decoration.bold.bold())); for (ClassVO c : matchedClasses) { table.row(label(c.getName()), label(c.getClassLoaderHash()).style(Decoration.bold.fg(Color.red)), TypeRenderUtils.drawClassLoader(c)); } return table; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/FileUtils.java
core/src/main/java/com/taobao/arthas/core/util/FileUtils.java
package com.taobao.arthas.core.util; /** * Copied from {@link org.apache.commons.io.FileUtils} * @author ralf0131 2016-12-28 11:46. */ import io.termd.core.util.Helper; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Properties; import com.taobao.arthas.common.ArthasConstants; public class FileUtils { /** * Writes a byte array to a file creating the file if it does not exist. * <p> * NOTE: As from v1.3, the parent directories of the file will be created * if they do not exist. * * @param file the file to write to * @param data the content to write to the file * @throws IOException in case of an I/O error * @since 1.1 */ public static void writeByteArrayToFile(File file, byte[] data) throws IOException { writeByteArrayToFile(file, data, false); } /** * Writes a byte array to a file creating the file if it does not exist. * * @param file the file to write to * @param data the content to write to the file * @param append if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since IO 2.1 */ public static void writeByteArrayToFile(File file, byte[] data, boolean append) throws IOException { try (OutputStream out = openOutputStream(file, append)) { out.write(data); } // ignore } /** * Opens a {@link FileOutputStream} for the specified file, checking and * creating the parent directory if it does not exist. * <p> * At the end of the method either the stream will be successfully opened, * or an exception will have been thrown. * <p> * The parent directory will be created if it does not exist. * The file will be created if it does not exist. * An exception is thrown if the file object exists but is a directory. * An exception is thrown if the file exists but cannot be written to. * An exception is thrown if the parent directory cannot be created. * * @param file the file to open for output, must not be {@code null} * @param append if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @return a new {@link FileOutputStream} for the specified file * @throws IOException if the file object is a directory * @throws IOException if the file cannot be written to * @throws IOException if a parent directory needs creating but that fails * @since 2.1 */ public static FileOutputStream openOutputStream(File file, boolean append) throws IOException { if (file.exists()) { if (file.isDirectory()) { throw new IOException("File '" + file + "' exists but is a directory"); } if (!file.canWrite()) { throw new IOException("File '" + file + "' cannot be written to"); } } else { File parent = file.getParentFile(); if (parent != null) { if (!parent.mkdirs() && !parent.isDirectory()) { throw new IOException("Directory '" + parent + "' could not be created"); } } } return new FileOutputStream(file, append); } private static boolean isAuthCommand(String command) { // 需要改写 auth command, TODO 更准确应该是用mask去掉密码信息 return command != null && command.trim().startsWith(ArthasConstants.AUTH); } private static final int[] AUTH_CODEPOINTS = Helper.toCodePoints(ArthasConstants.AUTH); /** * save the command history to the given file, data will be overridden. * @param history the command history, each represented by an int array * @param file the file to save the history */ public static void saveCommandHistory(List<int[]> history, File file) { try (OutputStream out = new BufferedOutputStream(openOutputStream(file, false))) { for (int[] command : history) { String commandStr = Helper.fromCodePoints(command); if (isAuthCommand(commandStr)) { command = AUTH_CODEPOINTS; } for (int i : command) { out.write(i); } out.write('\n'); } } catch (IOException e) { // ignore } // ignore } public static List<int[]> loadCommandHistory(File file) { BufferedReader br = null; List<int[]> history = new ArrayList<>(); try { br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String line; while ((line = br.readLine()) != null) { history.add(Helper.toCodePoints(line)); } } catch (IOException e) { // ignore } finally { try { if (br != null) { br.close(); } } catch (IOException ioe) { // ignore } } return history; } /** * save the command history to the given file, data will be overridden. * @param history the command history * @param file the file to save the history */ public static void saveCommandHistoryString(List<String> history, File file) { try (OutputStream out = new BufferedOutputStream(openOutputStream(file, false))) { for (String command : history) { if (!StringUtils.isBlank(command)) { if (isAuthCommand(command)) { command = ArthasConstants.AUTH; } out.write(command.getBytes("utf-8")); out.write('\n'); } } } catch (IOException e) { // ignore } // ignore } public static List<String> loadCommandHistoryString(File file) { BufferedReader br = null; List<String> history = new ArrayList<>(); try { br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8")); String line; while ((line = br.readLine()) != null) { if (!StringUtils.isBlank(line)) { history.add(line); } } } catch (IOException e) { // ignore } finally { try { if (br != null) { br.close(); } } catch (IOException ioe) { // ignore } } return history; } public static String readFileToString(File file, Charset encoding) throws IOException { try (FileInputStream stream = new FileInputStream(file)) { Reader reader = new BufferedReader(new InputStreamReader(stream, encoding)); StringBuilder builder = new StringBuilder(); char[] buffer = new char[8192]; int read; while ((read = reader.read(buffer, 0, buffer.length)) > 0) { builder.append(buffer, 0, read); } return builder.toString(); } } public static Properties readProperties(String file) throws IOException { Properties properties = new Properties(); FileInputStream in = null; try { in = new FileInputStream(file); properties.load(in); return properties; } finally { com.taobao.arthas.common.IOUtils.close(in); } } /** * Check if the given path is a directory or not exists. * @param path path of file. * @return {@code true} if the path is not exist or is an existing directory, otherwise returns {@code false}. */ public static boolean isDirectoryOrNotExist(String path) { File file = new File(path); return !file.exists() || file.isDirectory(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/IOUtils.java
core/src/main/java/com/taobao/arthas/core/util/IOUtils.java
package com.taobao.arthas.core.util; /** * Copied from {@link org.apache.commons.io.IOUtils} * @author ralf0131 2016-12-28 11:41. */ import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; public class IOUtils { private static final int EOF = -1; /** * The default buffer size ({@value}) to use for * {@link #copyLarge(InputStream, OutputStream)} */ private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; /** * Get the contents of an <code>InputStream</code> as a <code>byte[]</code>. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedInputStream</code>. * * @param input the <code>InputStream</code> to read from * @return the requested byte array * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs */ public static byte[] toByteArray(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); copy(input, output); return output.toByteArray(); } /** * Copy bytes from an <code>InputStream</code> to an * <code>OutputStream</code>. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedInputStream</code>. * <p> * Large streams (over 2GB) will return a bytes copied value of * <code>-1</code> after the copy has completed since the correct * number of bytes cannot be returned as an int. For large streams * use the <code>copyLarge(InputStream, OutputStream)</code> method. * * @param input the <code>InputStream</code> to read from * @param output the <code>OutputStream</code> to write to * @return the number of bytes copied, or -1 if &gt; Integer.MAX_VALUE * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 1.1 */ public static int copy(InputStream input, OutputStream output) throws IOException { long count = copyLarge(input, output); if (count > Integer.MAX_VALUE) { return -1; } return (int) count; } /** * Copy bytes from a large (over 2GB) <code>InputStream</code> to an * <code>OutputStream</code>. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedInputStream</code>. * <p> * The buffer size is given by {@link #DEFAULT_BUFFER_SIZE}. * * @param input the <code>InputStream</code> to read from * @param output the <code>OutputStream</code> to write to * @return the number of bytes copied * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 1.3 */ public static long copyLarge(InputStream input, OutputStream output) throws IOException { return copyLarge(input, output, new byte[DEFAULT_BUFFER_SIZE]); } /** * Copy bytes from a large (over 2GB) <code>InputStream</code> to an * <code>OutputStream</code>. * <p> * This method uses the provided buffer, so there is no need to use a * <code>BufferedInputStream</code>. * <p> * * @param input the <code>InputStream</code> to read from * @param output the <code>OutputStream</code> to write to * @param buffer the buffer to use for the copy * @return the number of bytes copied * @throws NullPointerException if the input or output is null * @throws IOException if an I/O error occurs * @since 2.2 */ public static long copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException { long count = 0; int n = 0; while (EOF != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } /** * Get the contents of an <code>InputStream</code> as a String * using the default character encoding of the platform. * <p> * This method buffers the input internally, so there is no need to use a * <code>BufferedInputStream</code>. * * @param input the <code>InputStream</code> to read from * @return the requested String * @throws NullPointerException if the input is null * @throws IOException if an I/O error occurs */ public static String toString(InputStream input) throws IOException { BufferedReader br = null; try { StringBuilder sb = new StringBuilder(); br = new BufferedReader(new InputStreamReader(input)); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { // ignore } } } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/TokenUtils.java
core/src/main/java/com/taobao/arthas/core/util/TokenUtils.java
package com.taobao.arthas.core.util; import java.util.List; import com.taobao.arthas.core.shell.cli.CliToken; /** * tokenizer helper * * @author gehui 2017-07-27 11:39:56 */ public class TokenUtils { /** * find the first text token */ public static CliToken findFirstTextToken(List<CliToken> tokens) { if (tokens == null || tokens.isEmpty()) { return null; } CliToken first = null; for (CliToken token : tokens) { if (token != null && token.isText()) { first = token; break; } } return first; } /** * find the last text token */ public static CliToken findLastTextToken(List<CliToken> tokens) { if (tokens == null || tokens.isEmpty()) { return null; } //#165 for (int i = tokens.size() - 1; i >= 0; i--) { CliToken token = tokens.get(i); if (token != null && token.isText()) { return token; } } return null; } /** * find the second text token's text */ public static String findSecondTokenText(List<CliToken> tokens) { if (tokens == null || tokens.isEmpty()) { return null; } boolean first = true; for (CliToken token : tokens) { if (token != null && token.isText()) { if (first) { first = false; } else { return token.value(); } } } return null; } public static CliToken getLast(List<CliToken> tokens) { if (tokens == null || tokens.isEmpty()) { return null; } else { return tokens.get(tokens.size() -1); } } public static String retrievePreviousArg(List<CliToken> tokens, String lastToken) { if (StringUtils.isBlank(lastToken) && tokens.size() > 2) { // tokens = { " ", "CLASS_NAME", " "} return tokens.get(tokens.size() - 2).value(); } else if (tokens.size() > 3) { // tokens = { " ", "CLASS_NAME", " ", "PARTIAL_METHOD_NAME"} return tokens.get(tokens.size() - 3).value(); } else { return Constants.EMPTY_STRING; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/DateUtils.java
core/src/main/java/com/taobao/arthas/core/util/DateUtils.java
package com.taobao.arthas.core.util; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; /** * @author diecui1202 on 2017/10/25. */ public final class DateUtils { private DateUtils() { throw new AssertionError(); } private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); public static String getCurrentDateTime() { return DATE_TIME_FORMATTER.format(LocalDateTime.now()); } public static String formatDateTime(LocalDateTime dateTime) { return DATE_TIME_FORMATTER.format(dateTime); } public static String getStartDateTime() { try { RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean(); long startTime = runtimeMXBean.getStartTime(); Instant startInstant = Instant.ofEpochMilli(startTime); LocalDateTime startDateTime = LocalDateTime.ofInstant(startInstant, ZoneId.systemDefault()); return DATE_TIME_FORMATTER.format(startDateTime); } catch (Throwable e) { return "unknown"; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/LogUtil.java
core/src/main/java/com/taobao/arthas/core/util/LogUtil.java
package com.taobao.arthas.core.util; import java.io.File; import java.util.Iterator; import com.alibaba.arthas.deps.ch.qos.logback.classic.LoggerContext; import com.alibaba.arthas.deps.ch.qos.logback.classic.joran.JoranConfigurator; import com.alibaba.arthas.deps.ch.qos.logback.classic.spi.ILoggingEvent; import com.alibaba.arthas.deps.ch.qos.logback.core.Appender; import com.alibaba.arthas.deps.ch.qos.logback.core.rolling.RollingFileAppender; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.taobao.arthas.common.AnsiLog; import com.taobao.arthas.core.env.ArthasEnvironment; /** * * @author hengyunabc * */ public class LogUtil { public static final String LOGGING_CONFIG_PROPERTY = "arthas.logging.config"; public static final String LOGGING_CONFIG = "${arthas.logging.config:${arthas.home}/logback.xml}"; /** * The name of the property that contains the name of the log file. Names can be * an exact location or relative to the current directory. */ public static final String FILE_NAME_PROPERTY = "arthas.logging.file.name"; public static final String ARTHAS_LOG_FILE = "ARTHAS_LOG_FILE"; /** * The name of the property that contains the directory where log files are * written. */ public static final String FILE_PATH_PROPERTY = "arthas.logging.file.path"; public static final String ARTHAS_LOG_PATH = "ARTHAS_LOG_PATH"; private static String logFile = ""; /** * <pre> * 1. 尝试从 arthas.logging.config 这个配置里加载 logback.xml * 2. 尝试从 arthas.home 下面找 logback.xml * * 可以用 arthas.logging.file.name 指定具体arthas.log的名字 * 可以用 arthas.logging.file.path 指定具体arthas.log的目录 * * </pre> * * @param env */ public static LoggerContext initLogger(ArthasEnvironment env) { String loggingConfig = env.resolvePlaceholders(LOGGING_CONFIG); if (loggingConfig == null || loggingConfig.trim().isEmpty()) { return null; } AnsiLog.debug("arthas logging file: " + loggingConfig); File configFile = new File(loggingConfig); if (!configFile.isFile()) { AnsiLog.error("can not find arthas logging config: " + loggingConfig); return null; } try { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.reset(); String fileName = env.getProperty(FILE_NAME_PROPERTY); if (fileName != null) { loggerContext.putProperty(ARTHAS_LOG_FILE, fileName); } String filePath = env.getProperty(FILE_PATH_PROPERTY); if (filePath != null) { loggerContext.putProperty(ARTHAS_LOG_PATH, filePath); } JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); configurator.doConfigure(configFile.toURI().toURL()); // load logback xml file // 查找 arthas.log appender Iterator<Appender<ILoggingEvent>> appenders = loggerContext.getLogger("root").iteratorForAppenders(); while (appenders.hasNext()) { Appender<ILoggingEvent> appender = appenders.next(); if (appender instanceof RollingFileAppender) { RollingFileAppender fileAppender = (RollingFileAppender) appender; if ("ARTHAS".equalsIgnoreCase(fileAppender.getName())) { logFile = new File(fileAppender.getFile()).getCanonicalPath(); } } } return loggerContext; } catch (Throwable e) { AnsiLog.error("try to load arthas logging config file error: " + configFile, e); } return null; } public static String loggingFile() { if (logFile == null || logFile.trim().isEmpty()) { return "arthas.log"; } return logFile; } public static String loggingDir() { if (logFile != null && !logFile.isEmpty()) { String parent = new File(logFile).getParent(); if (parent != null) { return parent; } } return new File("").getAbsolutePath(); } public static String cacheDir() { File logsDir = new File(loggingDir()).getParentFile(); if (logsDir.exists()) { File arthasCacheDir = new File(logsDir, "arthas-cache"); arthasCacheDir.mkdirs(); return arthasCacheDir.getAbsolutePath(); } else { File arthasCacheDir = new File("arthas-cache"); arthasCacheDir.mkdirs(); return arthasCacheDir.getAbsolutePath(); } } public static Logger getResultLogger() { return LoggerFactory.getLogger("result"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/ThreadLocalWatch.java
core/src/main/java/com/taobao/arthas/core/util/ThreadLocalWatch.java
package com.taobao.arthas.core.util; /** * 简单的调用计时器。 * * @author vlinux 16/6/1. * @author hengyunabc 2016-10-31 */ public class ThreadLocalWatch { /** * 用 long[] 做一个固定大小的 ring stack,避免把 ArthasClassLoader 加载的对象塞到业务线程的 ThreadLocalMap 里, * 从而在 stop/detach 后导致 ArthasClassLoader 无法被 GC 回收。 * * <pre> * 约定: * - stack[0] 存储当前 pos(0..cap) * - stack[1..cap] 存储数据 * </pre> */ private static final int DEFAULT_STACK_SIZE = 1024 * 4; private final ThreadLocal<long[]> timestampRef = ThreadLocal.withInitial(() -> new long[DEFAULT_STACK_SIZE + 1]); public long start() { final long timestamp = System.nanoTime(); push(timestampRef.get(), timestamp); return timestamp; } public long cost() { return (System.nanoTime() - pop(timestampRef.get())); } public double costInMillis() { return (System.nanoTime() - pop(timestampRef.get())) / 1000000.0; } /** * * <pre> * 一个特殊的stack,为了追求效率,避免扩容。 * 因为这个stack的push/pop 并不一定成对调用,比如可能push执行了,但是后面的流程被中断了,pop没有被执行。 * 如果不固定大小,一直增长的话,极端情况下可能应用有内存问题。 * 如果到达容量,pos会重置,循环存储数据。所以使用这个Stack如果在极端情况下统计的数据会不准确,只用于monitor/watch等命令的计时。 * * </pre> * * @author hengyunabc 2019-11-20 * */ static void push(long[] stack, long value) { int cap = stack.length - 1; int pos = (int) stack[0]; if (pos < cap) { pos++; } else { // if stack is full, reset pos pos = 1; } stack[pos] = value; stack[0] = pos; } static long pop(long[] stack) { int cap = stack.length - 1; int pos = (int) stack[0]; if (pos > 0) { long value = stack[pos]; stack[0] = pos - 1; return value; } pos = cap; long value = stack[pos]; stack[0] = pos - 1; return value; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/HttpUtils.java
core/src/main/java/com/taobao/arthas/core/util/HttpUtils.java
package com.taobao.arthas.core.util; import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.cookie.Cookie; import io.netty.handler.codec.http.cookie.ServerCookieEncoder; import java.io.UnsupportedEncodingException; import java.util.Set; /** * @author gongdewei 2020/3/31 */ public class HttpUtils { /** * Get cookie value by name * @param cookies request cookies * @param cookieName the cookie name */ public static String getCookieValue(Set<Cookie> cookies, String cookieName) { for (Cookie cookie : cookies) { if(cookie.name().equals(cookieName)){ return cookie.value(); } } return null; } /** * * @param response * @param name * @param value */ public static void setCookie(DefaultFullHttpResponse response, String name, String value) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(name, value)); } /** * Create http response with status code and content * @param request request * @param status response status code * @param content response content */ public static DefaultHttpResponse createResponse(FullHttpRequest request, HttpResponseStatus status, String content) { DefaultFullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), status); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=utf-8"); try { response.content().writeBytes(content.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { } return response; } public static HttpResponse createRedirectResponse(FullHttpRequest request, String url) { DefaultFullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.FOUND); response.headers().set(HttpHeaderNames.LOCATION, url); return response; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/Decompiler.java
core/src/main/java/com/taobao/arthas/core/util/Decompiler.java
package com.taobao.arthas.core.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.TreeMap; import org.benf.cfr.reader.api.CfrDriver; import org.benf.cfr.reader.api.OutputSinkFactory; import org.benf.cfr.reader.api.SinkReturns.LineNumberMapping; import com.taobao.arthas.common.Pair; /** * * @author hengyunabc 2018-11-16 * */ public class Decompiler { public static String decompile(String classFilePath, String methodName) { return decompile(classFilePath, methodName, false); } public static String decompile(String classFilePath, String methodName, boolean hideUnicode) { return decompile(classFilePath, methodName, hideUnicode, true); } public static Pair<String, NavigableMap<Integer, Integer>> decompileWithMappings(String classFilePath, String methodName, boolean hideUnicode, boolean printLineNumber) { final StringBuilder sb = new StringBuilder(8192); final NavigableMap<Integer, Integer> lineMapping = new TreeMap<Integer, Integer>(); OutputSinkFactory mySink = new OutputSinkFactory() { @Override public List<SinkClass> getSupportedSinks(SinkType sinkType, Collection<SinkClass> collection) { return Arrays.asList(SinkClass.STRING, SinkClass.DECOMPILED, SinkClass.DECOMPILED_MULTIVER, SinkClass.EXCEPTION_MESSAGE, SinkClass.LINE_NUMBER_MAPPING); } @Override public <T> Sink<T> getSink(final SinkType sinkType, final SinkClass sinkClass) { return new Sink<T>() { @Override public void write(T sinkable) { // skip message like: Analysing type demo.MathGame if (sinkType == SinkType.PROGRESS) { return; } if (sinkType == SinkType.LINENUMBER) { LineNumberMapping mapping = (LineNumberMapping) sinkable; NavigableMap<Integer, Integer> classFileMappings = mapping.getClassFileMappings(); NavigableMap<Integer, Integer> mappings = mapping.getMappings(); if (classFileMappings != null && mappings != null) { for (Entry<Integer, Integer> entry : mappings.entrySet()) { Integer srcLineNumber = classFileMappings.get(entry.getKey()); lineMapping.put(entry.getValue(), srcLineNumber); } } return; } sb.append(sinkable); } }; } }; HashMap<String, String> options = new HashMap<String, String>(); /** * @see org.benf.cfr.reader.util.MiscConstants.Version.getVersion() Currently, * the cfr version is wrong. so disable show cfr version. */ options.put("showversion", "false"); options.put("hideutf", String.valueOf(hideUnicode)); options.put("trackbytecodeloc", "true"); if (!StringUtils.isBlank(methodName)) { options.put("methodname", methodName); } CfrDriver driver = new CfrDriver.Builder().withOptions(options).withOutputSink(mySink).build(); List<String> toAnalyse = new ArrayList<String>(); toAnalyse.add(classFilePath); driver.analyse(toAnalyse); String resultCode = sb.toString(); if (printLineNumber && !lineMapping.isEmpty()) { resultCode = addLineNumber(resultCode, lineMapping); } return Pair.make(resultCode, lineMapping); } public static String decompile(String classFilePath, String methodName, boolean hideUnicode, boolean printLineNumber) { return decompileWithMappings(classFilePath, methodName, hideUnicode, printLineNumber).getFirst(); } private static String addLineNumber(String src, Map<Integer, Integer> lineMapping) { int maxLineNumber = 0; for (Integer value : lineMapping.values()) { if (value != null && value > maxLineNumber) { maxLineNumber = value; } } String formatStr = "/*%2d*/ "; String emptyStr = " "; StringBuilder sb = new StringBuilder(); List<String> lines = StringUtils.toLines(src); if (maxLineNumber >= 1000) { formatStr = "/*%4d*/ "; emptyStr = " "; } else if (maxLineNumber >= 100) { formatStr = "/*%3d*/ "; emptyStr = " "; } int index = 0; for (String line : lines) { Integer srcLineNumber = lineMapping.get(index + 1); if (srcLineNumber != null) { sb.append(String.format(formatStr, srcLineNumber)); } else { sb.append(emptyStr); } sb.append(line).append("\n"); index++; } return sb.toString(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/ThreadUtil.java
core/src/main/java/com/taobao/arthas/core/util/ThreadUtil.java
package com.taobao.arthas.core.util; import com.taobao.arthas.core.command.model.BlockingLockInfo; import com.taobao.arthas.core.command.model.BusyThreadInfo; import com.taobao.arthas.core.command.model.StackModel; import com.taobao.arthas.core.command.model.ThreadNode; import com.taobao.arthas.core.command.model.ThreadVO; import com.taobao.arthas.core.view.Ansi; import java.arthas.SpyAPI; import java.lang.management.*; import java.lang.reflect.Method; import java.util.*; /** * * @author hengyunabc 2015年12月7日 下午2:29:28 * */ abstract public class ThreadUtil { private static final BlockingLockInfo EMPTY_INFO = new BlockingLockInfo(); private static ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); private static boolean detectedEagleEye = false; public static boolean foundEagleEye = false; public static ThreadGroup getRoot() { ThreadGroup group = Thread.currentThread().getThreadGroup(); ThreadGroup parent; while ((parent = group.getParent()) != null) { group = parent; } return group; } /** * 获取所有线程 */ public static List<ThreadVO> getThreads() { ThreadGroup root = getRoot(); Thread[] threads = new Thread[root.activeCount()]; while (root.enumerate(threads, true) == threads.length) { threads = new Thread[threads.length * 2]; } List<ThreadVO> list = new ArrayList<ThreadVO>(threads.length); for (Thread thread : threads) { if (thread != null) { ThreadVO threadVO = createThreadVO(thread); list.add(threadVO); } } return list; } private static ThreadVO createThreadVO(Thread thread) { ThreadGroup group = thread.getThreadGroup(); ThreadVO threadVO = new ThreadVO(); threadVO.setId(thread.getId()); threadVO.setName(thread.getName()); threadVO.setGroup(group == null ? "" : group.getName()); threadVO.setPriority(thread.getPriority()); threadVO.setState(thread.getState()); threadVO.setInterrupted(thread.isInterrupted()); threadVO.setDaemon(thread.isDaemon()); return threadVO; } /** * 获取所有线程List * * @return */ public static List<Thread> getThreadList() { List<Thread> result = new ArrayList<Thread>(); ThreadGroup root = getRoot(); Thread[] threads = new Thread[root.activeCount()]; while (root.enumerate(threads, true) == threads.length) { threads = new Thread[threads.length * 2]; } for (Thread thread : threads) { if (thread != null) { result.add(thread); } } return result; } /** * Find the thread and lock that is blocking the most other threads. * * Time complexity of this algorithm: O(number of thread) * Space complexity of this algorithm: O(number of locks) * * @return the BlockingLockInfo object, or an empty object if not found. */ public static BlockingLockInfo findMostBlockingLock() { ThreadInfo[] infos = threadMXBean.dumpAllThreads(threadMXBean.isObjectMonitorUsageSupported(), threadMXBean.isSynchronizerUsageSupported()); // a map of <LockInfo.getIdentityHashCode, number of thread blocking on this> Map<Integer, Integer> blockCountPerLock = new HashMap<Integer, Integer>(); // a map of <LockInfo.getIdentityHashCode, the thread info that holding this lock Map<Integer, ThreadInfo> ownerThreadPerLock = new HashMap<Integer, ThreadInfo>(); for (ThreadInfo info: infos) { if (info == null) { continue; } LockInfo lockInfo = info.getLockInfo(); if (lockInfo != null) { // the current thread is blocked waiting on some condition if (blockCountPerLock.get(lockInfo.getIdentityHashCode()) == null) { blockCountPerLock.put(lockInfo.getIdentityHashCode(), 0); } int blockedCount = blockCountPerLock.get(lockInfo.getIdentityHashCode()); blockCountPerLock.put(lockInfo.getIdentityHashCode(), blockedCount + 1); } for (MonitorInfo monitorInfo: info.getLockedMonitors()) { // the object monitor currently held by this thread if (ownerThreadPerLock.get(monitorInfo.getIdentityHashCode()) == null) { ownerThreadPerLock.put(monitorInfo.getIdentityHashCode(), info); } } for (LockInfo lockedSync: info.getLockedSynchronizers()) { // the ownable synchronizer currently held by this thread if (ownerThreadPerLock.get(lockedSync.getIdentityHashCode()) == null) { ownerThreadPerLock.put(lockedSync.getIdentityHashCode(), info); } } } // find the thread that is holding the lock that blocking the largest number of threads. int mostBlockingLock = 0; // System.identityHashCode(null) == 0 int maxBlockingCount = 0; for (Map.Entry<Integer, Integer> entry: blockCountPerLock.entrySet()) { if (entry.getValue() > maxBlockingCount && ownerThreadPerLock.get(entry.getKey()) != null) { // the lock is explicitly held by anther thread. maxBlockingCount = entry.getValue(); mostBlockingLock = entry.getKey(); } } if (mostBlockingLock == 0) { // nothing found return EMPTY_INFO; } BlockingLockInfo blockingLockInfo = new BlockingLockInfo(); blockingLockInfo.setThreadInfo(ownerThreadPerLock.get(mostBlockingLock)); blockingLockInfo.setLockIdentityHashCode(mostBlockingLock); blockingLockInfo.setBlockingThreadCount(blockCountPerLock.get(mostBlockingLock)); return blockingLockInfo; } public static String getFullStacktrace(ThreadInfo threadInfo) { return getFullStacktrace(threadInfo, -1, -1, -1, 0, 0); } public static String getFullStacktrace(BlockingLockInfo blockingLockInfo) { return getFullStacktrace(blockingLockInfo.getThreadInfo(), -1, -1, -1, blockingLockInfo.getLockIdentityHashCode(), blockingLockInfo.getBlockingThreadCount()); } /** * 完全从 ThreadInfo 中 copy 过来 * @param threadInfo the thread info object * @param cpuUsage will be ignore if cpuUsage < 0 or cpuUsage > 100 * @param lockIdentityHashCode 阻塞了其他线程的锁的identityHashCode * @param blockingThreadCount 阻塞了其他线程的数量 * @return the string representation of the thread stack */ public static String getFullStacktrace(ThreadInfo threadInfo, double cpuUsage, long deltaTime, long time, int lockIdentityHashCode, int blockingThreadCount) { StringBuilder sb = new StringBuilder("\"" + threadInfo.getThreadName() + "\"" + " Id=" + threadInfo.getThreadId()); if (cpuUsage >= 0 && cpuUsage <= 100) { sb.append(" cpuUsage=").append(cpuUsage).append("%"); } if (deltaTime >= 0 ) { sb.append(" deltaTime=").append(deltaTime).append("ms"); } if (time >= 0 ) { sb.append(" time=").append(time).append("ms"); } sb.append(" ").append(threadInfo.getThreadState()); if (threadInfo.getLockName() != null) { sb.append(" on ").append(threadInfo.getLockName()); } if (threadInfo.getLockOwnerName() != null) { sb.append(" owned by \"").append(threadInfo.getLockOwnerName()).append("\" Id=").append(threadInfo.getLockOwnerId()); } if (threadInfo.isSuspended()) { sb.append(" (suspended)"); } if (threadInfo.isInNative()) { sb.append(" (in native)"); } sb.append('\n'); int i = 0; for (StackTraceElement ste : threadInfo.getStackTrace()) { sb.append("\tat ").append(ste.toString()); sb.append('\n'); if (i == 0 && threadInfo.getLockInfo() != null) { Thread.State ts = threadInfo.getThreadState(); switch (ts) { case BLOCKED: sb.append("\t- blocked on ").append(threadInfo.getLockInfo()); sb.append('\n'); break; case WAITING: sb.append("\t- waiting on ").append(threadInfo.getLockInfo()); sb.append('\n'); break; case TIMED_WAITING: sb.append("\t- waiting on ").append(threadInfo.getLockInfo()); sb.append('\n'); break; default: } } for (MonitorInfo mi : threadInfo.getLockedMonitors()) { if (mi.getLockedStackDepth() == i) { sb.append("\t- locked ").append(mi); if (mi.getIdentityHashCode() == lockIdentityHashCode) { Ansi highlighted = Ansi.ansi().fg(Ansi.Color.RED); highlighted.a(" <---- but blocks ").a(blockingThreadCount).a(" other threads!"); sb.append(highlighted.reset().toString()); } sb.append('\n'); } } ++i; } if (i < threadInfo.getStackTrace().length) { sb.append("\t..."); sb.append('\n'); } LockInfo[] locks = threadInfo.getLockedSynchronizers(); if (locks.length > 0) { sb.append("\n\tNumber of locked synchronizers = ").append(locks.length); sb.append('\n'); for (LockInfo li : locks) { sb.append("\t- ").append(li); if (li.getIdentityHashCode() == lockIdentityHashCode) { sb.append(" <---- but blocks ").append(blockingThreadCount); sb.append(" other threads!"); } sb.append('\n'); } } sb.append('\n'); return sb.toString().replace("\t", " "); } public static String getFullStacktrace(BusyThreadInfo threadInfo, int lockIdentityHashCode, int blockingThreadCount) { if (threadInfo == null) { return ""; } StringBuilder sb = new StringBuilder("\"" + threadInfo.getName() + "\""); if (threadInfo.getId() > 0) { sb.append(" Id=").append(threadInfo.getId()); } else { sb.append(" [Internal]"); } double cpuUsage = threadInfo.getCpu(); if (cpuUsage >= 0 && cpuUsage <= 100) { sb.append(" cpuUsage=").append(cpuUsage).append("%"); } if (threadInfo.getDeltaTime() >= 0 ) { sb.append(" deltaTime=").append(threadInfo.getDeltaTime()).append("ms"); } if (threadInfo.getTime() >= 0 ) { sb.append(" time=").append(threadInfo.getTime()).append("ms"); } if (threadInfo.getState() == null) { sb.append("\n\n"); return sb.toString(); } sb.append(" ").append(threadInfo.getState()); if (threadInfo.getLockName() != null) { sb.append(" on ").append(threadInfo.getLockName()); } if (threadInfo.getLockOwnerName() != null) { sb.append(" owned by \"").append(threadInfo.getLockOwnerName()).append("\" Id=").append(threadInfo.getLockOwnerId()); } if (threadInfo.isSuspended()) { sb.append(" (suspended)"); } if (threadInfo.isInNative()) { sb.append(" (in native)"); } sb.append('\n'); int i = 0; for (; i < threadInfo.getStackTrace().length; i++) { StackTraceElement ste = threadInfo.getStackTrace()[i]; sb.append("\tat ").append(ste.toString()); sb.append('\n'); if (i == 0 && threadInfo.getLockInfo() != null) { Thread.State ts = threadInfo.getState(); switch (ts) { case BLOCKED: sb.append("\t- blocked on ").append(threadInfo.getLockInfo()); sb.append('\n'); break; case WAITING: sb.append("\t- waiting on ").append(threadInfo.getLockInfo()); sb.append('\n'); break; case TIMED_WAITING: sb.append("\t- waiting on ").append(threadInfo.getLockInfo()); sb.append('\n'); break; default: } } for (MonitorInfo mi : threadInfo.getLockedMonitors()) { if (mi.getLockedStackDepth() == i) { sb.append("\t- locked ").append(mi); if (mi.getIdentityHashCode() == lockIdentityHashCode) { Ansi highlighted = Ansi.ansi().fg(Ansi.Color.RED); highlighted.a(" <---- but blocks ").a(blockingThreadCount).a(" other threads!"); sb.append(highlighted.reset().toString()); } sb.append('\n'); } } } if (i < threadInfo.getStackTrace().length) { sb.append("\t..."); sb.append('\n'); } LockInfo[] locks = threadInfo.getLockedSynchronizers(); if (locks.length > 0) { sb.append("\n\tNumber of locked synchronizers = ").append(locks.length); sb.append('\n'); for (LockInfo li : locks) { sb.append("\t- ").append(li); if (li.getIdentityHashCode() == lockIdentityHashCode) { sb.append(" <---- but blocks ").append(blockingThreadCount); sb.append(" other threads!"); } sb.append('\n'); } } sb.append('\n'); return sb.toString().replace("\t", " "); } /** * </pre> * java.lang.Thread.getStackTrace(Thread.java:1559), * com.taobao.arthas.core.util.ThreadUtil.getThreadStack(ThreadUtil.java:349), * com.taobao.arthas.core.command.monitor200.StackAdviceListener.before(StackAdviceListener.java:33), * com.taobao.arthas.core.advisor.AdviceListenerAdapter.before(AdviceListenerAdapter.java:49), * com.taobao.arthas.core.advisor.SpyImpl.atEnter(SpyImpl.java:42), * java.arthas.SpyAPI.atEnter(SpyAPI.java:40), * demo.MathGame.print(MathGame.java), demo.MathGame.run(MathGame.java:25), * demo.MathGame.main(MathGame.java:16) * </pre> */ private static int MAGIC_STACK_DEPTH = 0; private static int findTheSpyAPIDepth(StackTraceElement[] stackTraceElementArray) { if (MAGIC_STACK_DEPTH > 0) { return MAGIC_STACK_DEPTH; } if (MAGIC_STACK_DEPTH > stackTraceElementArray.length) { return 0; } for (int i = 0; i < stackTraceElementArray.length; ++i) { if (SpyAPI.class.getName().equals(stackTraceElementArray[i].getClassName())) { MAGIC_STACK_DEPTH = i + 1; break; } } return MAGIC_STACK_DEPTH; } /** * 获取方法执行堆栈信息 * * @return 方法堆栈信息 */ public static StackModel getThreadStackModel(ClassLoader loader, Thread currentThread) { StackModel stackModel = new StackModel(); stackModel.setThreadName(currentThread.getName()); stackModel.setThreadId(Long.toString(currentThread.getId())); stackModel.setDaemon(currentThread.isDaemon()); stackModel.setPriority(currentThread.getPriority()); stackModel.setClassloader(getTCCL(currentThread)); getEagleeyeTraceInfo(loader, currentThread, stackModel); //stack StackTraceElement[] stackTraceElementArray = currentThread.getStackTrace(); int magicStackDepth = findTheSpyAPIDepth(stackTraceElementArray); StackTraceElement[] actualStackFrames = new StackTraceElement[stackTraceElementArray.length - magicStackDepth]; System.arraycopy(stackTraceElementArray, magicStackDepth , actualStackFrames, 0, actualStackFrames.length); stackModel.setStackTrace(actualStackFrames); return stackModel; } public static ThreadNode getThreadNode(ClassLoader loader, Thread currentThread) { ThreadNode threadNode = new ThreadNode(); threadNode.setThreadId(currentThread.getId()); threadNode.setThreadName(currentThread.getName()); threadNode.setDaemon(currentThread.isDaemon()); threadNode.setPriority(currentThread.getPriority()); threadNode.setClassloader(getTCCL(currentThread)); //trace_id StackModel stackModel = new StackModel(); getEagleeyeTraceInfo(loader, currentThread, stackModel); threadNode.setTraceId(stackModel.getTraceId()); threadNode.setRpcId(stackModel.getRpcId()); return threadNode; } public static String getThreadTitle(StackModel stackModel) { StringBuilder sb = new StringBuilder("thread_name="); sb.append(stackModel.getThreadName()) .append(";id=").append(stackModel.getThreadId()) .append(";is_daemon=").append(stackModel.isDaemon()) .append(";priority=").append(stackModel.getPriority()) .append(";TCCL=").append(stackModel.getClassloader()); if (stackModel.getTraceId() != null) { sb.append(";trace_id=").append(stackModel.getTraceId()); } if (stackModel.getRpcId() != null) { sb.append(";rpc_id=").append(stackModel.getRpcId()); } return sb.toString(); } private static String getTCCL(Thread currentThread) { ClassLoader contextClassLoader = currentThread.getContextClassLoader(); if (null == contextClassLoader) { return "null"; } else { return contextClassLoader.getClass().getName() + "@" + Integer.toHexString(contextClassLoader.hashCode()); } } private static void getEagleeyeTraceInfo(ClassLoader loader, Thread currentThread, StackModel stackModel) { if(loader == null) { return; } Class<?> eagleEyeClass = null; if (!detectedEagleEye) { try { eagleEyeClass = loader.loadClass("com.taobao.eagleeye.EagleEye"); foundEagleEye = true; } catch (Throwable e) { // ignore } detectedEagleEye = true; } if (!foundEagleEye) { return; } try { if (eagleEyeClass == null) { eagleEyeClass = loader.loadClass("com.taobao.eagleeye.EagleEye"); } Method getTraceIdMethod = eagleEyeClass.getMethod("getTraceId"); String traceId = (String) getTraceIdMethod.invoke(null); stackModel.setTraceId(traceId); Method getRpcIdMethod = eagleEyeClass.getMethod("getRpcId"); String rpcId = (String) getRpcIdMethod.invoke(null); stackModel.setRpcId(rpcId); } catch (Throwable e) { // ignore } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/ArrayUtils.java
core/src/main/java/com/taobao/arthas/core/util/ArrayUtils.java
package com.taobao.arthas.core.util; /** * @author ralf0131 2016-12-28 14:57. */ public class ArrayUtils { /** * An empty immutable {@code long} array. */ public static final long[] EMPTY_LONG_ARRAY = new long[0]; /** * <p>Converts an array of object Longs to primitives.</p> * * <p>This method returns {@code null} for a {@code null} input array.</p> * * @param array a {@code Long} array, may be {@code null} * @return a {@code long} array, {@code null} if null array input * @throws NullPointerException if array content is {@code null} */ public static long[] toPrimitive(final Long[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_LONG_ARRAY; } final long[] result = new long[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].longValue(); } return result; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/NetUtils.java
core/src/main/java/com/taobao/arthas/core/util/NetUtils.java
package com.taobao.arthas.core.util; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import com.taobao.arthas.common.IOUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.Socket; import java.net.URL; /** * @author ralf0131 on 2015-11-11 15:39. */ public class NetUtils { private static final String QOS_HOST = "localhost"; private static final int QOS_PORT = 12201; private static final String QOS_RESPONSE_START_LINE = "pandora>[QOS Response]"; private static final int INTERNAL_SERVER_ERROR = 500; private static final int CONNECT_TIMEOUT = 1000; private static final int READ_TIMEOUT = 3000; /** * This implementation is based on Apache HttpClient. * @param urlString the requested url * @return the response string of given url */ public static Response request(String urlString) { HttpURLConnection urlConnection = null; InputStream in = null; try { URL url = new URL(urlString); urlConnection = (HttpURLConnection)url.openConnection(); urlConnection.setConnectTimeout(CONNECT_TIMEOUT); urlConnection.setReadTimeout(READ_TIMEOUT);; // prefer json to text urlConnection.setRequestProperty("Accept", "application/json,text/plain;q=0.2"); in = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } int statusCode = urlConnection.getResponseCode(); String result = sb.toString().trim(); if (statusCode == INTERNAL_SERVER_ERROR) { JSONObject errorObj = JSON.parseObject(result); if (errorObj.containsKey("errorMsg")) { return new Response(errorObj.getString("errorMsg"), false); } return new Response(result, false); } return new Response(result); } catch (IOException e) { return new Response(e.getMessage(), false); } finally { IOUtils.close(in); if (urlConnection != null) { urlConnection.disconnect(); } } } /** * @deprecated * This implementation is based on HttpURLConnection, * which can not detail with status code other than 200. * @param url the requested url * @return the response string of given url */ public static String simpleRequest(String url) { BufferedReader br = null; try { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestProperty("Accept", "application/json"); int responseCode = con.getResponseCode(); br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { sb.append(line); sb.append("\n"); } String result = sb.toString().trim(); if (responseCode == 500) { JSONObject errorObj = JSON.parseObject(result); if (errorObj.containsKey("errorMsg")) { return errorObj.getString("errorMsg"); } return result; } else { return result; } } catch (Exception e) { return null; } finally { if (br != null) { try { br.close(); } catch (IOException e) { // ignore } } } } /** * Only use this method when tomcat monitor version <= 1.0.1 * This will send http request to pandora qos port 12201, * and display the response. * Note that pandora qos response is not fully HTTP compatible under version 2.1.0, * so we filtered some of the content and only display useful content. * @param path the path relative to http://localhost:12201 * e.g. /pandora/ls * For commands that requires arguments, use the following format * e.g. /pandora/find?arg0=RPCProtocolService * Note that the parameter name is never used in pandora qos, * so the name(e.g. arg0) is irrelevant. * @return the qos response in string format */ public static Response requestViaSocket(String path) { BufferedReader br = null; try { Socket s = new Socket(QOS_HOST, QOS_PORT); PrintWriter pw = new PrintWriter(s.getOutputStream()); pw.println("GET " + path + " HTTP/1.1"); pw.println("Host: " + QOS_HOST + ":" + QOS_PORT); pw.println(""); pw.flush(); br = new BufferedReader(new InputStreamReader(s.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; boolean start = false; while ((line = br.readLine()) != null) { if (start) { sb.append(line).append("\n"); } if (line.equals(QOS_RESPONSE_START_LINE)) { start = true; } } String result = sb.toString().trim(); return new Response(result); } catch (Exception e) { return new Response(e.getMessage(), false); } finally { if (br != null) { try { br.close(); } catch (IOException e) { // ignore } } } } public static class Response { private boolean success; private String content; public Response(String content, boolean success) { this.success = success; this.content = content; } public Response(String content) { this.content = content; this.success = true; } public boolean isSuccess() { return success; } public String getContent() { return content; } } /** * Test if a port is open on the give host */ public static boolean serverListening(String host, int port) { Socket s = null; try { s = new Socket(host, port); return true; } catch (Exception e) { return false; } finally { if (s != null) { try { s.close(); } catch (Exception e) { // ignore } } } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/ClassLoaderUtils.java
core/src/main/java/com/taobao/arthas/core/util/ClassLoaderUtils.java
package com.taobao.arthas.core.util; import java.lang.instrument.Instrumentation; import java.lang.reflect.Field; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; /** * * @author hengyunabc 2019-02-05 * */ public class ClassLoaderUtils { private static Logger logger = LoggerFactory.getLogger(ClassLoaderUtils.class); public static Set<ClassLoader> getAllClassLoader(Instrumentation inst) { Set<ClassLoader> classLoaderSet = new HashSet<ClassLoader>(); for (Class<?> clazz : inst.getAllLoadedClasses()) { ClassLoader classLoader = clazz.getClassLoader(); if (classLoader != null) { classLoaderSet.add(classLoader); } } return classLoaderSet; } public static ClassLoader getClassLoader(Instrumentation inst, String hashCode) { if (hashCode == null || hashCode.isEmpty()) { return null; } for (Class<?> clazz : inst.getAllLoadedClasses()) { ClassLoader classLoader = clazz.getClassLoader(); if (classLoader != null) { if (Integer.toHexString(classLoader.hashCode()).equals(hashCode)) { return classLoader; } } } return null; } /** * 通过类名查找classloader * @param inst * @param classLoaderClassName * @return */ public static List<ClassLoader> getClassLoaderByClassName(Instrumentation inst, String classLoaderClassName) { if (classLoaderClassName == null || classLoaderClassName.isEmpty()) { return null; } Set<ClassLoader> classLoaderSet = getAllClassLoader(inst); List<ClassLoader> matchClassLoaders = new ArrayList<ClassLoader>(); for (ClassLoader classLoader : classLoaderSet) { if (classLoader.getClass().getName().equals(classLoaderClassName)) { matchClassLoaders.add(classLoader); } } return matchClassLoaders; } public static String classLoaderHash(ClassLoader classLoader) { int hashCode = 0; if (classLoader == null) { hashCode = System.identityHashCode(classLoader); } else { hashCode = classLoader.hashCode(); } if (hashCode <= 0) { hashCode = System.identityHashCode(classLoader); if (hashCode < 0) { hashCode = hashCode & Integer.MAX_VALUE; } } return Integer.toHexString(hashCode); } /** * Find List<ClassLoader> by the class name of ClassLoader or the return value of ClassLoader#toString(). * @param inst * @param classLoaderClassName * @param classLoaderToString * @return */ public static List<ClassLoader> getClassLoader(Instrumentation inst, String classLoaderClassName, String classLoaderToString) { List<ClassLoader> matchClassLoaders = new ArrayList<ClassLoader>(); if (StringUtils.isEmpty(classLoaderClassName) && StringUtils.isEmpty(classLoaderToString)) { return matchClassLoaders; } Set<ClassLoader> classLoaderSet = getAllClassLoader(inst); List<ClassLoader> matchedByClassLoaderToStr = new ArrayList<ClassLoader>(); for (ClassLoader classLoader : classLoaderSet) { // only classLoaderClassName if (!StringUtils.isEmpty(classLoaderClassName) && StringUtils.isEmpty(classLoaderToString)) { if (classLoader.getClass().getName().equals(classLoaderClassName)) { matchClassLoaders.add(classLoader); } } // only classLoaderToString else if (!StringUtils.isEmpty(classLoaderToString) && StringUtils.isEmpty(classLoaderClassName)) { if (classLoader.toString().equals(classLoaderToString)) { matchClassLoaders.add(classLoader); } } // classLoaderClassName and classLoaderToString else { if (classLoader.getClass().getName().equals(classLoaderClassName)) { matchClassLoaders.add(classLoader); } if (classLoader.toString().equals(classLoaderToString)) { matchedByClassLoaderToStr.add(classLoader); } } } // classLoaderClassName and classLoaderToString if (!StringUtils.isEmpty(classLoaderClassName) && !StringUtils.isEmpty(classLoaderToString)) { matchClassLoaders.retainAll(matchedByClassLoaderToStr); } return matchClassLoaders; } @SuppressWarnings({ "unchecked", "restriction" }) public static URL[] getUrls(ClassLoader classLoader) { if (classLoader instanceof URLClassLoader) { try { return ((URLClassLoader) classLoader).getURLs(); } catch (Throwable e) { logger.error("classLoader: {} getUrls error", classLoader, e); } } // jdk9 if (classLoader.getClass().getName().startsWith("jdk.internal.loader.ClassLoaders$")) { try { Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); sun.misc.Unsafe unsafe = (sun.misc.Unsafe) field.get(null); Class<?> ucpOwner = classLoader.getClass(); Field ucpField = null; // jdk 9~15: jdk.internal.loader.ClassLoaders$AppClassLoader.ucp // jdk 16~17: jdk.internal.loader.BuiltinClassLoader.ucp while (ucpField == null && !ucpOwner.getName().equals("java.lang.Object")) { try { ucpField = ucpOwner.getDeclaredField("ucp"); } catch (NoSuchFieldException ex) { ucpOwner = ucpOwner.getSuperclass(); } } if (ucpField == null) { return null; } long ucpFieldOffset = unsafe.objectFieldOffset(ucpField); Object ucpObject = unsafe.getObject(classLoader, ucpFieldOffset); if (ucpObject == null) { return null; } // jdk.internal.loader.URLClassPath.path Field pathField = ucpField.getType().getDeclaredField("path"); if (pathField == null) { return null; } long pathFieldOffset = unsafe.objectFieldOffset(pathField); ArrayList<URL> path = (ArrayList<URL>) unsafe.getObject(ucpObject, pathFieldOffset); return path.toArray(new URL[path.size()]); } catch (Throwable e) { // ignore return null; } } return null; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/ArthasCheckUtils.java
core/src/main/java/com/taobao/arthas/core/util/ArthasCheckUtils.java
package com.taobao.arthas.core.util; /** * Utils for checks * Created by vlinux on 15/5/19. */ public class ArthasCheckUtils { /** * check whether a component is in an Array<br/> * * @param e component * @param s array * @param <E> component type * @return <br/> * (1,1,2,3) == true * (1,2,3,4) == false * (null,1,null,2) == true * (1,null) == false */ public static <E> boolean isIn(E e, E... s) { if (null != s) { for (E es : s) { if (isEquals(e, es)) { return true; } } } return false; } /** * check whether two components are equal<br/> * * @param src source component * @param target target component * @param <E> component type * @return <br/> * (null, null) == true * (1L,2L) == false * (1L,1L) == true * ("abc",null) == false * (null,"abc") == false */ public static <E> boolean isEquals(E src, E target) { return null == src && null == target || null != src && null != target && src.equals(target); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/CommandUtils.java
core/src/main/java/com/taobao/arthas/core/util/CommandUtils.java
package com.taobao.arthas.core.util; import com.taobao.arthas.core.shell.command.CommandProcess; import com.taobao.arthas.core.shell.command.ExitStatus; /** * Command Process util */ public class CommandUtils { /** * check exit status and end command processing * @param process CommandProcess instance * @param status ExitStatus of command */ public static void end(CommandProcess process, ExitStatus status) { if (status != null) { process.end(status.getStatusCode(), status.getMessage()); } else { process.end(-1, "process error, exit status is null"); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/Constants.java
core/src/main/java/com/taobao/arthas/core/util/Constants.java
package com.taobao.arthas.core.util; import java.io.File; import com.taobao.arthas.common.PidUtils; import com.taobao.arthas.core.view.Ansi; /** * @author ralf0131 2016-12-28 16:20. */ public class Constants { private Constants() { } /** * 中断提示 */ public static final String Q_OR_CTRL_C_ABORT_MSG = "Press Q or Ctrl+C to abort."; /** * 空字符串 */ public static final String EMPTY_STRING = ""; /** * 命令提示符 */ public static final String DEFAULT_PROMPT = "$ "; /** * 带颜色命令提示符 * raw string: "[33m$ " */ public static final String COLOR_PROMPT = Ansi.ansi().fg(Ansi.Color.YELLOW).a(DEFAULT_PROMPT).reset().toString(); /** * 方法执行耗时 */ public static final String COST_VARIABLE = "cost"; public static final String CMD_HISTORY_FILE = System.getProperty("user.home") + File.separator + ".arthas" + File.separator + "history"; /** * 当前进程PID */ public static final String PID = PidUtils.currentPid(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/InstrumentationUtils.java
core/src/main/java/com/taobao/arthas/core/util/InstrumentationUtils.java
package com.taobao.arthas.core.util; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.Instrumentation; import java.util.Collection; import java.util.Set; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; /** * * @author hengyunabc 2020-05-25 * */ public class InstrumentationUtils { private static final Logger logger = LoggerFactory.getLogger(InstrumentationUtils.class); public static void retransformClasses(Instrumentation inst, ClassFileTransformer transformer, Set<Class<?>> classes) { try { inst.addTransformer(transformer, true); for (Class<?> clazz : classes) { if (ClassUtils.isLambdaClass(clazz)) { logger.info( "ignore lambda class: {}, because jdk do not support retransform lambda class: https://github.com/alibaba/arthas/issues/1512.", clazz.getName()); continue; } try { inst.retransformClasses(clazz); } catch (Throwable e) { String errorMsg = "retransformClasses class error, name: " + clazz.getName(); logger.error(errorMsg, e); } } } finally { inst.removeTransformer(transformer); } } public static void trigerRetransformClasses(Instrumentation inst, Collection<String> classes) { for (Class<?> clazz : inst.getAllLoadedClasses()) { if (classes.contains(clazz.getName())) { try { inst.retransformClasses(clazz); } catch (Throwable e) { String errorMsg = "retransformClasses class error, name: " + clazz.getName(); logger.error(errorMsg, e); } } } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/SearchUtils.java
core/src/main/java/com/taobao/arthas/core/util/SearchUtils.java
package com.taobao.arthas.core.util; import com.taobao.arthas.core.GlobalOptions; import com.taobao.arthas.core.util.matcher.Matcher; import com.taobao.arthas.core.util.matcher.RegexMatcher; import com.taobao.arthas.core.util.matcher.WildcardMatcher; import java.lang.instrument.Instrumentation; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * 类搜索工具 * Created by vlinux on 15/5/17. * @author diecui1202 on 2017/09/07. */ public class SearchUtils { /** * 根据类名匹配,搜索已经被JVM加载的类 * * @param inst inst * @param classNameMatcher 类名匹配 * @param limit 最大匹配限制 * @return 匹配的类集合 */ public static Set<Class<?>> searchClass(Instrumentation inst, Matcher<String> classNameMatcher, int limit) { if (classNameMatcher == null) { return Collections.emptySet(); } final Set<Class<?>> matches = new HashSet<Class<?>>(); for (Class<?> clazz : inst.getAllLoadedClasses()) { if (clazz == null) { continue; } if (classNameMatcher.matching(clazz.getName())) { matches.add(clazz); } if (matches.size() >= limit) { break; } } return matches; } public static Set<Class<?>> searchClass(Instrumentation inst, Matcher<String> classNameMatcher) { return searchClass(inst, classNameMatcher, Integer.MAX_VALUE); } public static Set<Class<?>> searchClass(Instrumentation inst, String classPattern, boolean isRegEx) { Matcher<String> classNameMatcher = classNameMatcher(classPattern, isRegEx); return GlobalOptions.isDisableSubClass ? searchClass(inst, classNameMatcher) : searchSubClass(inst, searchClass(inst, classNameMatcher)); } public static Set<Class<?>> searchClass(Instrumentation inst, String classPattern, boolean isRegEx, String code) { Set<Class<?>> matchedClasses = searchClass(inst, classPattern, isRegEx); return filter(matchedClasses, code); } public static Set<Class<?>> searchClassOnly(Instrumentation inst, String classPattern, boolean isRegEx) { Matcher<String> classNameMatcher = classNameMatcher(classPattern, isRegEx); return searchClass(inst, classNameMatcher); } public static Set<Class<?>> searchClassOnly(Instrumentation inst, String classPattern, int limit) { Matcher<String> classNameMatcher = classNameMatcher(classPattern, false); return searchClass(inst, classNameMatcher, limit); } public static Set<Class<?>> searchClassOnly(Instrumentation inst, String classPattern, boolean isRegEx, String code) { Set<Class<?>> matchedClasses = searchClassOnly(inst, classPattern, isRegEx); return filter(matchedClasses, code); } private static Set<Class<?>> filter(Set<Class<?>> matchedClasses, String code) { if (code == null) { return matchedClasses; } Set<Class<?>> result = new HashSet<Class<?>>(); if (matchedClasses != null) { for (Class<?> c : matchedClasses) { if (c.getClassLoader() != null && Integer.toHexString(c.getClassLoader().hashCode()).equals(code)) { result.add(c); } } } return result; } public static Matcher<String> classNameMatcher(String classPattern, boolean isRegEx) { if (StringUtils.isEmpty(classPattern)) { classPattern = isRegEx ? ".*" : "*"; } if (!classPattern.contains("$$Lambda")) { classPattern = StringUtils.replace(classPattern, "/", "."); } return isRegEx ? new RegexMatcher(classPattern) : new WildcardMatcher(classPattern); } /** * 搜索目标类的子类 * * @param inst inst * @param classSet 当前类集合 * @return 匹配的子类集合 */ public static Set<Class<?>> searchSubClass(Instrumentation inst, Set<Class<?>> classSet) { final Set<Class<?>> matches = new HashSet<Class<?>>(); for (Class<?> clazz : inst.getAllLoadedClasses()) { if (clazz == null) { continue; } for (Class<?> superClass : classSet) { if (superClass.isAssignableFrom(clazz)) { matches.add(clazz); break; } } } return matches; } /** * 搜索目标类的内部类 * * @param inst inst * @param c 当前类 * @return 匹配的类的集合 */ public static Set<Class<?>> searchInnerClass(Instrumentation inst, Class<?> c) { final Set<Class<?>> matches = new HashSet<Class<?>>(); for (Class<?> clazz : inst.getInitiatedClasses(c.getClassLoader())) { if (c.getClassLoader() != null && clazz.getClassLoader() != null && c.getClassLoader().equals(clazz.getClassLoader())) { if (clazz.getName().startsWith(c.getName())) { matches.add(clazz); } } } return matches; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/matcher/EqualsMatcher.java
core/src/main/java/com/taobao/arthas/core/util/matcher/EqualsMatcher.java
package com.taobao.arthas.core.util.matcher; import com.taobao.arthas.core.util.ArthasCheckUtils; /** * 字符串全匹配 * @author ralf0131 2017-01-06 13:18. */ public class EqualsMatcher<T> implements Matcher<T> { private final T pattern; public EqualsMatcher(T pattern) { this.pattern = pattern; } @Override public boolean matching(T target) { return ArthasCheckUtils.isEquals(target, pattern); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/matcher/FalseMatcher.java
core/src/main/java/com/taobao/arthas/core/util/matcher/FalseMatcher.java
package com.taobao.arthas.core.util.matcher; /** * @author ralf0131 2017-01-06 13:33. */ public class FalseMatcher<T> implements Matcher<T> { /** * always return false * @param target * @return true/false */ @Override public boolean matching(T target) { return false; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/matcher/RegexMatcher.java
core/src/main/java/com/taobao/arthas/core/util/matcher/RegexMatcher.java
package com.taobao.arthas.core.util.matcher; /** * regex matcher * @author ralf0131 2017-01-06 13:16. */ public class RegexMatcher implements Matcher<String> { private final String pattern; public RegexMatcher(String pattern) { this.pattern = pattern; } @Override public boolean matching(String target) { return null != target && null != pattern && target.matches(pattern); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/matcher/TrueMatcher.java
core/src/main/java/com/taobao/arthas/core/util/matcher/TrueMatcher.java
package com.taobao.arthas.core.util.matcher; /** * @author ralf0131 2017-01-06 13:48. */ public final class TrueMatcher<T> implements Matcher<T> { /** * always return true * @param target * @return */ @Override public boolean matching(T target) { return true; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/matcher/Matcher.java
core/src/main/java/com/taobao/arthas/core/util/matcher/Matcher.java
package com.taobao.arthas.core.util.matcher; /** * 匹配器 * Created by vlinux on 15/5/17. */ public interface Matcher<T> { /** * 是否匹配 * * @param target 目标字符串 * @return 目标字符串是否匹配表达式 */ boolean matching(T target); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/matcher/WildcardMatcher.java
core/src/main/java/com/taobao/arthas/core/util/matcher/WildcardMatcher.java
package com.taobao.arthas.core.util.matcher; /** * wildcard matcher * @author ralf0131 2017-01-06 13:17. */ public class WildcardMatcher implements Matcher<String> { private final String pattern; private static final Character ASTERISK = '*'; private static final Character QUESTION_MARK = '?'; private static final Character ESCAPE = '\\'; public WildcardMatcher(String pattern) { this.pattern = pattern; } @Override public boolean matching(String target) { return match(target, pattern, 0, 0); } /** * Internal matching recursive function. */ private boolean match(String target, String pattern, int stringStartNdx, int patternStartNdx) { //#135 if(target==null || pattern==null){ return false; } int pNdx = patternStartNdx; int sNdx = stringStartNdx; int pLen = pattern.length(); if (pLen == 1) { // speed-up if (pattern.charAt(0) == ASTERISK) { return true; } } int sLen = target.length(); boolean nextIsNotWildcard = false; while (true) { // check if end of string and/or pattern occurred if ((sNdx >= sLen)) { // end of string still may have pending '*' callback pattern while ((pNdx < pLen) && (pattern.charAt(pNdx) == ASTERISK)) { pNdx++; } return pNdx >= pLen; } // end of pattern, but not end of the string if (pNdx >= pLen) { return false; } // pattern char char p = pattern.charAt(pNdx); // perform logic if (!nextIsNotWildcard) { if (p == ESCAPE) { pNdx++; nextIsNotWildcard = true; continue; } if (p == QUESTION_MARK) { sNdx++; pNdx++; continue; } if (p == ASTERISK) { // next pattern char char pnext = 0; if (pNdx + 1 < pLen) { pnext = pattern.charAt(pNdx + 1); } // double '*' have the same effect as one '*' if (pnext == ASTERISK) { pNdx++; continue; } int i; pNdx++; // find recursively if there is any substring from the end of the // line that matches the rest of the pattern !!! for (i = target.length(); i >= sNdx; i--) { if (match(target, pattern, i, pNdx)) { return true; } } return false; } } else { nextIsNotWildcard = false; } // check if pattern char and string char are equals if (p != target.charAt(sNdx)) { return false; } // everything matches for now, continue sNdx++; pNdx++; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/matcher/GroupMatcher.java
core/src/main/java/com/taobao/arthas/core/util/matcher/GroupMatcher.java
package com.taobao.arthas.core.util.matcher; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; /** * @author ralf0131 2017-01-06 13:29. */ public interface GroupMatcher<T> extends Matcher<T> { /** * 追加匹配器 * * @param matcher 匹配器 */ void add(Matcher<T> matcher); /** * 与关系组匹配 * * @param <T> 匹配类型 */ class And<T> implements GroupMatcher<T> { private final Collection<Matcher<T>> matchers; /** * 与关系组匹配构造<br/> * 当且仅当目标符合匹配组的所有条件时才判定匹配成功 * * @param matchers 待进行与关系组匹配的匹配集合 */ public And(Matcher<T>... matchers) { this.matchers = Arrays.asList(matchers); } @Override public boolean matching(T target) { for (Matcher<T> matcher : matchers) { if (!matcher.matching(target)) { return false; } } return true; } @Override public void add(Matcher<T> matcher) { matchers.add(matcher); } } /** * 或关系组匹配 * * @param <T> 匹配类型 */ class Or<T> implements GroupMatcher<T> { private final Collection<Matcher<T>> matchers; public Or() { this.matchers = new ArrayList<Matcher<T>>(); } /** * 或关系组匹配构造<br/> * 当且仅当目标符合匹配组的任一条件时就判定匹配成功 * * @param matchers 待进行或关系组匹配的匹配集合 */ public Or(Matcher<T>... matchers) { this.matchers = Arrays.asList(matchers); } public Or(Collection<Matcher<T>> matchers) { this.matchers = matchers; } @Override public boolean matching(T target) { for (Matcher<T> matcher : matchers) { if (matcher.matching(target)) { return true; } } return false; } @Override public void add(Matcher<T> matcher) { matchers.add(matcher); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/affect/EnhancerAffect.java
core/src/main/java/com/taobao/arthas/core/util/affect/EnhancerAffect.java
package com.taobao.arthas.core.util.affect; import com.taobao.arthas.core.GlobalOptions; import com.taobao.arthas.core.util.ClassLoaderUtils; import java.io.File; import java.lang.instrument.ClassFileTransformer; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static java.lang.String.format; /** * 增强影响范围<br/> * 统计影响类/方法/耗时 * Created by vlinux on 15/5/19. * @author hengyunabc 2020-06-01 */ public final class EnhancerAffect extends Affect { private final AtomicInteger cCnt = new AtomicInteger(); private final AtomicInteger mCnt = new AtomicInteger(); private ClassFileTransformer transformer; private long listenerId; private Throwable throwable; /** * dumpClass的文件存放集合 */ private final Collection<File> classDumpFiles = new ArrayList<File>(); private final List<String> methods = new ArrayList<String>(); private String overLimitMsg; public EnhancerAffect() { } /** * 影响类统计 * * @param cc 类影响计数 * @return 当前影响类个数 */ public int cCnt(int cc) { return cCnt.addAndGet(cc); } /** * 影响方法统计 * * @param mc 方法影响计数 * @return 当前影响方法个数 */ public int mCnt(int mc) { return mCnt.addAndGet(mc); } /** * 记录影响的函数,并增加计数 * @param mc * @return */ public int addMethodAndCount(ClassLoader classLoader, String clazz, String method, String methodDesc) { this.methods.add(ClassLoaderUtils.classLoaderHash(classLoader) + "|" + clazz.replace('/', '.') + "#" + method + "|" + methodDesc); return mCnt.addAndGet(1); } /** * 获取影响类个数 * * @return 影响类个数 */ public int cCnt() { return cCnt.get(); } /** * 获取影响方法个数 * * @return 影响方法个数 */ public int mCnt() { return mCnt.get(); } public void addClassDumpFile(File file) { classDumpFiles.add(file); } public ClassFileTransformer getTransformer() { return transformer; } public void setTransformer(ClassFileTransformer transformer) { this.transformer = transformer; } public long getListenerId() { return listenerId; } public void setListenerId(long listenerId) { this.listenerId = listenerId; } public Throwable getThrowable() { return throwable; } public void setThrowable(Throwable throwable) { this.throwable = throwable; } public Collection<File> getClassDumpFiles() { return classDumpFiles; } public List<String> getMethods() { return methods; } public String getOverLimitMsg() { return overLimitMsg; } public void setOverLimitMsg(String overLimitMsg) { this.overLimitMsg = overLimitMsg; } @Override public String toString() { //TODO removing EnhancerAffect.toString(), replace with ViewRenderUtil.renderEnhancerAffect() final StringBuilder infoSB = new StringBuilder(); if (GlobalOptions.isDump && !classDumpFiles.isEmpty()) { for (File classDumpFile : classDumpFiles) { infoSB.append("[dump: ").append(classDumpFile.getAbsoluteFile()).append("]\n"); } } if (GlobalOptions.verbose && !methods.isEmpty()) { for (String method : methods) { infoSB.append("[Affect method: ").append(method).append("]\n"); } } infoSB.append(format("Affect(class count: %d , method count: %d) cost in %s ms, listenerId: %d", cCnt(), mCnt(), cost(), listenerId)); if (this.throwable != null) { infoSB.append("\nEnhance error! exception: ").append(this.throwable); } return infoSB.toString(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/affect/RowAffect.java
core/src/main/java/com/taobao/arthas/core/util/affect/RowAffect.java
package com.taobao.arthas.core.util.affect; import java.util.concurrent.atomic.AtomicInteger; /** * 行记录影响反馈 * Created by vlinux on 15/5/21. */ public final class RowAffect extends Affect { private final AtomicInteger rCnt = new AtomicInteger(); public RowAffect() { } public RowAffect(int rCnt) { this.rCnt(rCnt); } /** * 影响行数统计 * * @param mc 行影响计数 * @return 当前影响行个数 */ public int rCnt(int mc) { return rCnt.addAndGet(mc); } /** * 获取影响行个数 * * @return 影响行个数 */ public int rCnt() { return rCnt.get(); } @Override public String toString() { return String.format("Affect(row-cnt:%d) cost in %s ms.", rCnt(), cost()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/affect/Affect.java
core/src/main/java/com/taobao/arthas/core/util/affect/Affect.java
package com.taobao.arthas.core.util.affect; import static java.lang.System.currentTimeMillis; /** * 影响反馈 * Created by vlinux on 15/5/21. * @author diecui1202 on 2017/10/26 */ public class Affect { private final long start = currentTimeMillis(); /** * 影响耗时(ms) * * @return 获取耗时(ms) */ public long cost() { return currentTimeMillis() - start; } @Override public String toString() { return String.format("Affect cost in %s ms.", cost()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/metrics/SumRateCounter.java
core/src/main/java/com/taobao/arthas/core/util/metrics/SumRateCounter.java
package com.taobao.arthas.core.util.metrics; /** * <pre> * 统计传入的数据是总数的速率。 * 比如传入的数据是所有请求的数量,5秒数据为: * 267, 457, 635, 894, 1398 * 则统计的平均速率是:( (457-267) + (635-457) + (894-635) + (1398-894) ) / 4 = 282 * </pre> * * @author hengyunabc 2015年12月18日 下午3:40:26 * */ public class SumRateCounter { RateCounter rateCounter; Long previous = null; public SumRateCounter() { rateCounter = new RateCounter(); } public SumRateCounter(int size) { rateCounter = new RateCounter(size); } public int size() { return rateCounter.size(); } public void update(long value) { if (previous == null) { previous = value; return; } rateCounter.update(value - previous); previous = value; } public double rate() { return rateCounter.rate(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/metrics/RateCounter.java
core/src/main/java/com/taobao/arthas/core/util/metrics/RateCounter.java
package com.taobao.arthas.core.util.metrics; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLongArray; import java.util.concurrent.ThreadLocalRandom; /** * <pre> * 统计平均速率,比如统计5秒内的平均速率。 * 5秒的数据是:234, 345,124,366,235, * 则速率是 (234+345+124+366+235)/5 = 260 * * </pre> * * @author hengyunabc 2015年12月18日 下午3:40:19 * */ public class RateCounter { private static final int BITS_PER_LONG = 63; public static final int DEFAULT_SIZE = 5; private final AtomicLong count = new AtomicLong(); private final AtomicLongArray values; public RateCounter() { this(DEFAULT_SIZE); } public RateCounter(int size) { this.values = new AtomicLongArray(size); for (int i = 0; i < values.length(); i++) { values.set(i, 0); } count.set(0); } public int size() { final long c = count.get(); if (c > values.length()) { return values.length(); } return (int) c; } public void update(long value) { final long c = count.incrementAndGet(); if (c <= values.length()) { values.set((int) c - 1, value); } else { final long r = nextLong(c); if (r < values.length()) { values.set((int) r, value); } } } public double rate() { long c = count.get(); int countLength = 0; long sum = 0; if (c > values.length()) { countLength = values.length(); } else { countLength = (int) c; } for (int i = 0; i < countLength; ++i) { sum += values.get(i); } return sum / (double) countLength; } /** * Get a pseudo-random long uniformly between 0 and n-1. Stolen from * {@link java.util.Random#nextInt()}. * * @param n * the bound * @return a value select randomly from the range {@code [0..n)}. */ private static long nextLong(long n) { long bits, val; do { bits = ThreadLocalRandom.current().nextLong() & (~(1L << BITS_PER_LONG)); val = bits % n; } while (bits - val + (n - 1) < 0L); return val; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/collection/GaStack.java
core/src/main/java/com/taobao/arthas/core/util/collection/GaStack.java
package com.taobao.arthas.core.util.collection; /** * 堆栈 * Created by vlinux on 15/6/21. * @param <E> */ public interface GaStack<E> { E pop(); void push(E e); E peek(); boolean isEmpty(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/collection/ThreadUnsafeFixGaStack.java
core/src/main/java/com/taobao/arthas/core/util/collection/ThreadUnsafeFixGaStack.java
package com.taobao.arthas.core.util.collection; import java.util.NoSuchElementException; /** * 线程不安全固定栈深的堆栈实现<br/> * 固定堆栈深度的实现能比JDK自带的堆栈实现提高10倍的性能. * Created by vlinux on 15/6/21. * @param <E> */ public class ThreadUnsafeFixGaStack<E> implements GaStack<E> { private final static int EMPTY_INDEX = -1; private final Object[] elementArray; private final int max; private int current = EMPTY_INDEX; public ThreadUnsafeFixGaStack(int max) { this.max = max; this.elementArray = new Object[max]; } private void checkForPush() { // stack is full if (current == max) { throw new ArrayIndexOutOfBoundsException(); } } private void checkForPopOrPeek() { // stack is empty if (isEmpty()) { throw new NoSuchElementException(); } } @Override public E pop() { checkForPopOrPeek(); return (E) elementArray[current--]; } @Override public void push(E e) { checkForPush(); elementArray[++current] = e; } @Override public E peek() { checkForPopOrPeek(); return (E) elementArray[current]; } @Override public boolean isEmpty() { return current == EMPTY_INDEX; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/collection/ThreadUnsafeGaStack.java
core/src/main/java/com/taobao/arthas/core/util/collection/ThreadUnsafeGaStack.java
package com.taobao.arthas.core.util.collection; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import java.util.NoSuchElementException; import static java.lang.System.arraycopy; /** * 线程不安全不固定栈深的堆栈实现<br/> * 比默认的实现带来3倍的性能提升 * Created by vlinux on 15/6/21. * * @param <E> */ public class ThreadUnsafeGaStack<E> implements GaStack<E> { private static final Logger logger = LoggerFactory.getLogger(ThreadUnsafeGaStack.class); private final static int EMPTY_INDEX = -1; private final static int DEFAULT_STACK_DEEP = 12; private Object[] elementArray; private int current = EMPTY_INDEX; public ThreadUnsafeGaStack() { this(DEFAULT_STACK_DEEP); } private ThreadUnsafeGaStack(int stackSize) { this.elementArray = new Object[stackSize]; } /** * 自动扩容<br/> * 当前堆栈最大深度不满足期望时会自动扩容(2倍扩容) * * @param expectDeep 期望堆栈深度 */ private void ensureCapacityInternal(int expectDeep) { final int currentStackSize = elementArray.length; if (elementArray.length <= expectDeep) { if (logger.isDebugEnabled()) { logger.debug("resize GaStack to double length: " + currentStackSize * 2 + " for thread: " + Thread.currentThread().getName()); } final Object[] newElementArray = new Object[currentStackSize * 2]; arraycopy(elementArray, 0, newElementArray, 0, currentStackSize); this.elementArray = newElementArray; } } private void checkForPopOrPeek() { // stack is empty if (isEmpty()) { throw new NoSuchElementException(); } } @Override public E pop() { try { checkForPopOrPeek(); E res = (E) elementArray[current]; elementArray[current] = null; current--; return res; } finally { if (current == EMPTY_INDEX && elementArray.length > DEFAULT_STACK_DEEP) { elementArray = new Object[DEFAULT_STACK_DEEP]; if (logger.isDebugEnabled()) { logger.debug("resize GaStack to default length for thread: " + Thread.currentThread().getName()); } } } } @Override public void push(E e) { ensureCapacityInternal(current + 1); elementArray[++current] = e; } @Override public E peek() { checkForPopOrPeek(); return (E) elementArray[current]; } @Override public boolean isEmpty() { return current == EMPTY_INDEX; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
core/src/main/java/com/taobao/arthas/core/util/reflect/FieldUtils.java
package com.taobao.arthas.core.util.reflect; import com.taobao.arthas.core.util.StringUtils; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; /** * @author ralf0131 2016-12-28 14:39. */ public class FieldUtils { private static final int ACCESS_TEST = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE; /** * Reads the named {@code public} {@link Field}. Only the class of the specified object will be considered. * * @param target * the object to reflect, must not be {@code null} * @param fieldName * the field name to obtain * @return the value of the field * @throws IllegalArgumentException * if {@code target} is {@code null}, or the field name is blank or empty or could not be found * @throws IllegalAccessException * if the named field is not {@code public} */ public static Object readDeclaredField(final Object target, final String fieldName) throws IllegalAccessException { return readDeclaredField(target, fieldName, false); } /** * Gets a {@link Field} value by name. Only the class of the specified object will be considered. * * @param target * the object to reflect, must not be {@code null} * @param fieldName * the field name to obtain * @param forceAccess * whether to break scope restrictions using the * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only * match public fields. * @return the Field object * @throws IllegalArgumentException * if {@code target} is {@code null}, or the field name is blank or empty or could not be found * @throws IllegalAccessException * if the field is not made accessible */ public static Object readDeclaredField(final Object target, final String fieldName, final boolean forceAccess) throws IllegalAccessException { isTrue(target != null, "target object must not be null"); final Class<?> cls = target.getClass(); final Field field = getDeclaredField(cls, fieldName, forceAccess); isTrue(field != null, "Cannot locate declared field %s.%s", cls, fieldName); // already forced access above, don't repeat it here: return readField(field, target, false); } /** * Gets an accessible {@link Field} by name, breaking scope if requested. Only the specified class will be * considered. * * @param cls * the {@link Class} to reflect, must not be {@code null} * @param fieldName * the field name to obtain * @param forceAccess * whether to break scope restrictions using the * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only * match {@code public} fields. * @return the Field object * @throws IllegalArgumentException * if the class is {@code null}, or the field name is blank or empty */ public static Field getDeclaredField(final Class<?> cls, final String fieldName, final boolean forceAccess) { isTrue(cls != null, "The class must not be null"); isTrue(!StringUtils.isBlank(fieldName), "The field name must not be blank/empty"); try { // only consider the specified class by using getDeclaredField() final Field field = cls.getDeclaredField(fieldName); if (!isAccessible(field)) { if (forceAccess) { field.setAccessible(true); } else { return null; } } return field; } catch (final NoSuchFieldException e) { // NOPMD // ignore } return null; } /** * Reads a {@link Field}. * * @param field * the field to use * @param target * the object to call on, may be {@code null} for {@code static} fields * @param forceAccess * whether to break scope restrictions using the * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. * @return the field value * @throws IllegalArgumentException * if the field is {@code null} * @throws IllegalAccessException * if the field is not made accessible */ public static Object readField(final Field field, final Object target, final boolean forceAccess) throws IllegalAccessException { isTrue(field != null, "The field must not be null"); if (forceAccess && !field.isAccessible()) { field.setAccessible(true); } else { setAccessibleWorkaround(field); } return field.get(target); } /** * Reads an accessible {@code static} {@link Field}. * * @param field * to read * @return the field value * @throws IllegalArgumentException * if the field is {@code null}, or not {@code static} * @throws IllegalAccessException * if the field is not accessible */ public static Object readStaticField(final Field field) throws IllegalAccessException { return readStaticField(field, false); } /** * Reads a static {@link Field}. * * @param field * to read * @param forceAccess * whether to break scope restrictions using the * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. * @return the field value * @throws IllegalArgumentException * if the field is {@code null} or not {@code static} * @throws IllegalAccessException * if the field is not made accessible */ public static Object readStaticField(final Field field, final boolean forceAccess) throws IllegalAccessException { isTrue(field != null, "The field must not be null"); isTrue(Modifier.isStatic(field.getModifiers()), "The field '%s' is not static", field.getName()); return readField(field, (Object) null, forceAccess); } /** * Writes a {@code public static} {@link Field}. * * @param field * to write * @param value * to set * @throws IllegalArgumentException * if the field is {@code null} or not {@code static}, or {@code value} is not assignable * @throws IllegalAccessException * if the field is not {@code public} or is {@code final} */ public static void writeStaticField(final Field field, final Object value) throws IllegalAccessException { writeStaticField(field, value, false); } /** * Writes a static {@link Field}. * * @param field * to write * @param value * to set * @param forceAccess * whether to break scope restrictions using the * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only * match {@code public} fields. * @throws IllegalArgumentException * if the field is {@code null} or not {@code static}, or {@code value} is not assignable * @throws IllegalAccessException * if the field is not made accessible or is {@code final} */ public static void writeStaticField(final Field field, final Object value, final boolean forceAccess) throws IllegalAccessException { isTrue(field != null, "The field must not be null"); isTrue(Modifier.isStatic(field.getModifiers()), "The field %s.%s is not static", field.getDeclaringClass().getName(), field.getName()); writeField(field, (Object) null, value, forceAccess); } /** * Writes a {@link Field}. * * @param field * to write * @param target * the object to call on, may be {@code null} for {@code static} fields * @param value * to set * @param forceAccess * whether to break scope restrictions using the * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only * match {@code public} fields. * @throws IllegalArgumentException * if the field is {@code null} or {@code value} is not assignable * @throws IllegalAccessException * if the field is not made accessible or is {@code final} */ public static void writeField(final Field field, final Object target, final Object value, final boolean forceAccess) throws IllegalAccessException { isTrue(field != null, "The field must not be null"); if (forceAccess && !field.isAccessible()) { field.setAccessible(true); } else { setAccessibleWorkaround(field); } field.set(target, value); } /** * Gets all fields of the given class and its parents (if any). * * @param cls * the {@link Class} to query * @return an array of Fields (possibly empty). * @throws IllegalArgumentException * if the class is {@code null} * @since 3.2 */ public static Field[] getAllFields(final Class<?> cls) { final List<Field> allFieldsList = getAllFieldsList(cls); return allFieldsList.toArray(new Field[0]); } /** * Gets all fields of the given class and its parents (if any). * * @param cls * the {@link Class} to query * @return an array of Fields (possibly empty). * @throws IllegalArgumentException * if the class is {@code null} * @since 3.2 */ public static List<Field> getAllFieldsList(final Class<?> cls) { isTrue(cls != null, "The class must not be null"); final List<Field> allFields = new ArrayList<Field>(); Class<?> currentClass = cls; while (currentClass != null) { final Field[] declaredFields = currentClass.getDeclaredFields(); allFields.addAll(Arrays.asList(declaredFields)); currentClass = currentClass.getSuperclass(); } return allFields; } /** * Gets an accessible {@link Field} by name respecting scope. Superclasses/interfaces will be considered. * * @param cls * the {@link Class} to reflect, must not be {@code null} * @param fieldName * the field name to obtain * @return the Field object * @throws IllegalArgumentException * if the class is {@code null}, or the field name is blank or empty */ public static Field getField(final Class<?> cls, final String fieldName) { final Field field = getField(cls, fieldName, false); setAccessibleWorkaround(field); return field; } /** * Gets an accessible {@link Field} by name, breaking scope if requested. Superclasses/interfaces will be * considered. * * @param cls * the {@link Class} to reflect, must not be {@code null} * @param fieldName * the field name to obtain * @param forceAccess * whether to break scope restrictions using the * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only * match {@code public} fields. * @return the Field object * @throws IllegalArgumentException * if the class is {@code null}, or the field name is blank or empty or is matched at multiple places * in the inheritance hierarchy */ public static Field getField(final Class<?> cls, final String fieldName, final boolean forceAccess) { isTrue(cls != null, "The class must not be null"); isTrue(!StringUtils.isBlank(fieldName), "The field name must not be blank/empty"); // FIXME is this workaround still needed? lang requires Java 6 // Sun Java 1.3 has a bugged implementation of getField hence we write the // code ourselves // getField() will return the Field object with the declaring class // set correctly to the class that declares the field. Thus requesting the // field on a subclass will return the field from the superclass. // // priority order for lookup: // searchclass private/protected/package/public // superclass protected/package/public // private/different package blocks access to further superclasses // implementedinterface public // check up the superclass hierarchy for (Class<?> acls = cls; acls != null; acls = acls.getSuperclass()) { try { final Field field = acls.getDeclaredField(fieldName); // getDeclaredField checks for non-public scopes as well // and it returns accurate results if (!Modifier.isPublic(field.getModifiers())) { if (forceAccess) { field.setAccessible(true); } else { continue; } } return field; } catch (final NoSuchFieldException ex) { // NOPMD // ignore } } // check the public interface case. This must be manually searched for // incase there is a public supersuperclass field hidden by a private/package // superclass field. Field match = null; for (final Class<?> class1 : getAllInterfaces(cls)) { try { final Field test = class1.getField(fieldName); isTrue(match == null, "Reference to field %s is ambiguous relative to %s" + "; a matching field exists on two or more implemented interfaces.", fieldName, cls); match = test; } catch (final NoSuchFieldException ex) { // NOPMD // ignore } } return match; } /** * <p>Gets a {@code List} of all interfaces implemented by the given * class and its superclasses.</p> * * <p>The order is determined by looking through each interface in turn as * declared in the source file and following its hierarchy up. Then each * superclass is considered in the same way. Later duplicates are ignored, * so the order is maintained.</p> * * @param cls the class to look up, may be {@code null} * @return the {@code List} of interfaces in order, * {@code null} if null input */ public static List<Class<?>> getAllInterfaces(final Class<?> cls) { if (cls == null) { return null; } final LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<Class<?>>(); getAllInterfaces(cls, interfacesFound); return new ArrayList<Class<?>>(interfacesFound); } /** * Get the interfaces for the specified class. * * @param cls the class to look up, may be {@code null} * @param interfacesFound the {@code Set} of interfaces for the class */ private static void getAllInterfaces(Class<?> cls, final HashSet<Class<?>> interfacesFound) { while (cls != null) { final Class<?>[] interfaces = cls.getInterfaces(); for (final Class<?> i : interfaces) { if (interfacesFound.add(i)) { getAllInterfaces(i, interfacesFound); } } cls = cls.getSuperclass(); } } /** * XXX Default access superclass workaround. * * When a {@code public} class has a default access superclass with {@code public} members, * these members are accessible. Calling them from compiled code works fine. * Unfortunately, on some JVMs, using reflection to invoke these members * seems to (wrongly) prevent access even when the modifier is {@code public}. * Calling {@code setAccessible(true)} solves the problem but will only work from * sufficiently privileged code. Better workarounds would be gratefully * accepted. * @param o the AccessibleObject to set as accessible * @return a boolean indicating whether the accessibility of the object was set to true. */ static boolean setAccessibleWorkaround(final AccessibleObject o) { if (o == null || o.isAccessible()) { return false; } final Member m = (Member) o; if (!o.isAccessible() && Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) { try { o.setAccessible(true); return true; } catch (final SecurityException e) { // NOPMD // ignore in favor of subsequent IllegalAccessException } } return false; } /** * Returns whether a given set of modifiers implies package access. * @param modifiers to test * @return {@code true} unless {@code package}/{@code protected}/{@code private} modifier detected */ static boolean isPackageAccess(final int modifiers) { return (modifiers & ACCESS_TEST) == 0; } /** * Returns whether a {@link Member} is accessible. * @param m Member to check * @return {@code true} if <code>m</code> is accessible */ static boolean isAccessible(final Member m) { return m != null && Modifier.isPublic(m.getModifiers()) && !m.isSynthetic(); } static void isTrue(final boolean expression, final String message, final Object... values) { if (!expression) { throw new IllegalArgumentException(String.format(message, values)); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/reflect/ArthasReflectUtils.java
core/src/main/java/com/taobao/arthas/core/util/reflect/ArthasReflectUtils.java
package com.taobao.arthas.core.util.reflect; import com.taobao.arthas.core.util.ArthasCheckUtils; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * 反射工具类 Created by vlinux on 15/5/18. */ public class ArthasReflectUtils { /** * 从包package中获取所有的Class * * @param packname 包名称 * @return 包路径下所有类集合 * <p> * 代码摘抄自 http://www.oschina.net/code/snippet_129830_8767</p> */ public static Set<Class<?>> getClasses(final ClassLoader loader, final String packname) { // 第一个class类的集合 Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); // 是否循环迭代 // 获取包的名字 并进行替换 String packageName = packname; String packageDirName = packageName.replace('.', '/'); // 定义一个枚举的集合 并进行循环来处理这个目录下的things Enumeration<URL> dirs; try { // dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); dirs = loader.getResources(packageDirName); // 循环迭代下去 while (dirs.hasMoreElements()) { // 获取下一个元素 URL url = dirs.nextElement(); // 得到协议的名称 String protocol = url.getProtocol(); // 如果是以文件的形式保存在服务器上 if ("file".equals(protocol)) { // System.err.println("file类型的扫描"); // 获取包的物理路径 String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); // 以文件的方式扫描整个包下的文件 并添加到集合中 findAndAddClassesInPackageByFile(packageName, filePath, true, classes); } else if ("jar".equals(protocol)) { // 如果是jar包文件 // 定义一个JarFile // System.err.println("jar类型的扫描"); JarFile jar; try { // 获取jar jar = ((JarURLConnection) url.openConnection()) .getJarFile(); // 从此jar包 得到一个枚举类 Enumeration<JarEntry> entries = jar.entries(); // 同样的进行循环迭代 while (entries.hasMoreElements()) { // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件 JarEntry entry = entries.nextElement(); String name = entry.getName(); // 如果是以/开头的 if (name.charAt(0) == '/') { // 获取后面的字符串 name = name.substring(1); } // 如果前半部分和定义的包名相同 if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); // 如果以"/"结尾 是一个包 if (idx != -1) { // 获取包名 把"/"替换成"." packageName = name.substring(0, idx) .replace('/', '.'); } // 如果是一个.class文件 而且不是目录 if (name.endsWith(".class") && !entry.isDirectory()) { // 去掉后面的".class" 获取真正的类名 String className = name.substring( packageName.length() + 1, name.length() - 6); try { // 添加到classes classes.add(Class .forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { // log // .error("添加用户自定义视图类错误 找不到此类的.class文件"); // e.printStackTrace(); } } } } } catch (IOException e) { // log.error("在扫描用户定义视图时从jar包获取文件出错"); // e.printStackTrace(); } } } } catch (IOException e) { // e.printStackTrace(); } return classes; } /** * 以文件的形式来获取包下的所有Class * <p/> * <p> * 代码摘抄自 http://www.oschina.net/code/snippet_129830_8767</p> */ private static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, Set<Class<?>> classes) { // 获取此包的目录 建立一个File File dir = new File(packagePath); // 如果不存在或者 也不是目录就直接返回 if (!dir.exists() || !dir.isDirectory()) { // log.warn("用户定义包名 " + packageName + " 下没有任何文件"); return; } // 如果存在 就获取包下的所有文件 包括目录 File[] dirfiles = dir.listFiles(new FileFilter() { // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件) @Override public boolean accept(File file) { return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); } }); if (dirfiles != null) { // 循环所有文件 for (File file : dirfiles) { // 如果是目录 则继续扫描 if (file.isDirectory()) { findAndAddClassesInPackageByFile( packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes); } else { // 如果是java类文件 去掉后面的.class 只留下类名 String className = file.getName().substring(0, file.getName().length() - 6); try { // 添加到集合中去 // classes.add(Class.forName(packageName + '.' + // className)); // 经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净 classes.add(Thread.currentThread().getContextClassLoader() .loadClass(packageName + '.' + className)); } catch (ClassNotFoundException e) { // log.error("添加用户自定义视图类错误 找不到此类的.class文件"); // e.printStackTrace(); } } } } } /** * 设置对象某个成员的值 * * @param field 属性对象 * @param value 属性值 * @param target 目标对象 * @throws IllegalArgumentException 非法参数 * @throws IllegalAccessException 非法进入 */ public static void set(Field field, Object value, Object target) throws IllegalArgumentException, IllegalAccessException { final boolean isAccessible = field.isAccessible(); try { field.setAccessible(true); field.set(target, value); } finally { field.setAccessible(isAccessible); } } /** * 获取一个类下的所有成员(包括父类、私有成员) * * @param clazz 目标类 * @return 类下所有属性 */ public static Set<Field> getFields(Class<?> clazz) { final Set<Field> fields = new LinkedHashSet<Field>(); final Class<?> parentClazz = clazz.getSuperclass(); Collections.addAll(fields, clazz.getDeclaredFields()); if (null != parentClazz) { fields.addAll(getFields(parentClazz)); } return fields; } /** * 获取一个类下的指定成员 * * @param clazz 目标类 * @param name 属性名 * @return 属性 */ public static Field getField(Class<?> clazz, String name) { for (Field field : getFields(clazz)) { if (ArthasCheckUtils.isEquals(field.getName(), name)) { return field; } }//for return null; } /** * 获取对象某个成员的值 * * @param <T> * @param target 目标对象 * @param field 目标属性 * @return 目标属性值 * @throws IllegalArgumentException 非法参数 * @throws IllegalAccessException 非法进入 */ public static <T> T getFieldValueByField(Object target, Field field) throws IllegalArgumentException, IllegalAccessException { final boolean isAccessible = field.isAccessible(); try { field.setAccessible(true); //noinspection unchecked return (T) field.get(target); } finally { field.setAccessible(isAccessible); } } /** * 将字符串转换为指定类型,目前只支持9种类型:8种基本类型(包括其包装类)以及字符串 * * @param t 目标对象类型 * @param value 目标值 * @return 类型转换后的值 */ @SuppressWarnings("unchecked") public static <T> T valueOf(Class<T> t, String value) { if (ArthasCheckUtils.isIn(t, int.class, Integer.class)) { return (T) Integer.valueOf(value); } else if (ArthasCheckUtils.isIn(t, long.class, Long.class)) { return (T) Long.valueOf(value); } else if (ArthasCheckUtils.isIn(t, double.class, Double.class)) { return (T) Double.valueOf(value); } else if (ArthasCheckUtils.isIn(t, float.class, Float.class)) { return (T) Float.valueOf(value); } else if (ArthasCheckUtils.isIn(t, char.class, Character.class)) { return (T) Character.valueOf(value.charAt(0)); } else if (ArthasCheckUtils.isIn(t, byte.class, Byte.class)) { return (T) Byte.valueOf(value); } else if (ArthasCheckUtils.isIn(t, boolean.class, Boolean.class)) { return (T) Boolean.valueOf(value); } else if (ArthasCheckUtils.isIn(t, short.class, Short.class)) { return (T) Short.valueOf(value); } else if (ArthasCheckUtils.isIn(t, String.class)) { return (T) value; } else { return null; } } /** * 定义类 * * @param targetClassLoader 目标classloader * @param className 类名称 * @param classByteArray 类字节码数组 * @return 定义的类 * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ public static Class<?> defineClass( final ClassLoader targetClassLoader, final String className, final byte[] classByteArray) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { final Method defineClassMethod = ClassLoader.class.getDeclaredMethod( "defineClass", String.class, byte[].class, int.class, int.class ); synchronized (defineClassMethod) { final boolean acc = defineClassMethod.isAccessible(); try { defineClassMethod.setAccessible(true); return (Class<?>) defineClassMethod.invoke( targetClassLoader, className, classByteArray, 0, classByteArray.length ); } finally { defineClassMethod.setAccessible(acc); } } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/util/usage/StyledUsageFormatter.java
core/src/main/java/com/taobao/arthas/core/util/usage/StyledUsageFormatter.java
package com.taobao.arthas.core.util.usage; import com.taobao.middleware.cli.Argument; import com.taobao.middleware.cli.CLI; import com.taobao.middleware.cli.Option; import com.taobao.middleware.cli.UsageMessageFormatter; import com.taobao.text.Color; import com.taobao.text.Decoration; import com.taobao.text.Style; import com.taobao.text.ui.TableElement; import com.taobao.text.util.RenderUtil; import java.util.Collections; import static com.taobao.text.ui.Element.row; import static com.taobao.text.ui.Element.label; /** * @author ralf0131 2016-12-14 22:16. */ public class StyledUsageFormatter extends UsageMessageFormatter { private Color fontColor; public StyledUsageFormatter(Color fontColor) { this.fontColor = fontColor; } public static String styledUsage(CLI cli, int width) { if(cli == null) { return ""; } StringBuilder usageBuilder = new StringBuilder(); UsageMessageFormatter formatter = new StyledUsageFormatter(Color.green); formatter.setWidth(width); cli.usage(usageBuilder, formatter); return usageBuilder.toString(); } @Override public void usage(StringBuilder builder, String prefix, CLI cli) { TableElement table = new TableElement(1, 2).leftCellPadding(1).rightCellPadding(1); table.add(row().add(label("USAGE:").style(getHighlightedStyle()))); table.add(row().add(label(computeUsageLine(prefix, cli)))); table.add(row().add("")); table.add(row().add(label("SUMMARY:").style(getHighlightedStyle()))); table.add(row().add(label(" " + cli.getSummary()))); if (cli.getDescription() != null) { String[] descLines = cli.getDescription().split("\\n"); for (String line: descLines) { if (shouldBeHighlighted(line)) { table.add(row().add(label(line).style(getHighlightedStyle()))); } else { table.add(row().add(label(line))); } } } if (!cli.getOptions().isEmpty() || !cli.getArguments().isEmpty()) { table.add(row().add("")); table.row(label("OPTIONS:").style(getHighlightedStyle())); for (Option option : cli.getOptions()) { StringBuilder optionSb = new StringBuilder(32); // short name if (isNullOrEmpty(option.getShortName())) { optionSb.append(" "); } else { optionSb.append('-').append(option.getShortName()); if (isNullOrEmpty(option.getLongName())) { optionSb.append(' '); } else { optionSb.append(','); } } // long name if (!isNullOrEmpty(option.getLongName())) { optionSb.append(" --").append(option.getLongName()); } if (option.acceptValue()) { optionSb.append(" <value>"); } table.add(row().add(label(optionSb.toString()).style(getHighlightedStyle())) .add(option.getDescription())); } for (Argument argument: cli.getArguments()) { table.add(row().add(label("<" + argument.getArgName() + ">").style(getHighlightedStyle())) .add(argument.getDescription())); } } builder.append(RenderUtil.render(table, getWidth())); } private Style.Composite getHighlightedStyle() { return Style.style(Decoration.bold, fontColor); } public String computeUsageLine(String prefix, CLI cli) { // initialise the string buffer StringBuilder buff; if (prefix == null) { buff = new StringBuilder(" "); } else { buff = new StringBuilder(" ").append(prefix); if (!prefix.endsWith(" ")) { buff.append(" "); } } buff.append(cli.getName()).append(" "); if (getOptionComparator() != null) { Collections.sort(cli.getOptions(), getOptionComparator()); } // iterate over the options for (Option option : cli.getOptions()) { appendOption(buff, option); buff.append(" "); } // iterate over the arguments for (Argument arg : cli.getArguments()) { appendArgument(buff, arg, arg.isRequired()); buff.append(" "); } return buff.toString(); } private boolean shouldBeHighlighted(String line) { return !line.startsWith(" "); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/MissingRequiredPropertiesException.java
core/src/main/java/com/taobao/arthas/core/env/MissingRequiredPropertiesException.java
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; import java.util.LinkedHashSet; import java.util.Set; /** * Exception thrown when required properties are not found. * * @author Chris Beams * @since 3.1 * @see ConfigurablePropertyResolver#setRequiredProperties(String...) * @see ConfigurablePropertyResolver#validateRequiredProperties() * @see org.springframework.context.support.AbstractApplicationContext#prepareRefresh() */ @SuppressWarnings("serial") public class MissingRequiredPropertiesException extends IllegalStateException { private final Set<String> missingRequiredProperties = new LinkedHashSet<String>(); void addMissingRequiredProperty(String key) { this.missingRequiredProperties.add(key); } @Override public String getMessage() { return "The following properties were declared as required but could not be resolved: " + getMissingRequiredProperties(); } /** * Return the set of properties marked as required but not present upon * validation. * * @see ConfigurablePropertyResolver#setRequiredProperties(String...) * @see ConfigurablePropertyResolver#validateRequiredProperties() */ public Set<String> getMissingRequiredProperties() { return this.missingRequiredProperties; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/AbstractPropertyResolver.java
core/src/main/java/com/taobao/arthas/core/env/AbstractPropertyResolver.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; import com.taobao.arthas.core.env.convert.ConfigurableConversionService; import com.taobao.arthas.core.env.convert.DefaultConversionService; /** * Abstract base class for resolving properties against any underlying source. * * @author Chris Beams * @author Juergen Hoeller * @since 3.1 */ public abstract class AbstractPropertyResolver implements ConfigurablePropertyResolver { protected ConfigurableConversionService conversionService = new DefaultConversionService(); private PropertyPlaceholderHelper nonStrictHelper; private PropertyPlaceholderHelper strictHelper; private boolean ignoreUnresolvableNestedPlaceholders = false; private String placeholderPrefix = SystemPropertyUtils.PLACEHOLDER_PREFIX; private String placeholderSuffix = SystemPropertyUtils.PLACEHOLDER_SUFFIX; private String valueSeparator = SystemPropertyUtils.VALUE_SEPARATOR; private final Set<String> requiredProperties = new LinkedHashSet<String>(); public ConfigurableConversionService getConversionService() { return this.conversionService; } public void setConversionService(ConfigurableConversionService conversionService) { this.conversionService = conversionService; } /** * Set the prefix that placeholders replaced by this resolver must begin with. * <p> * The default is "${". * * @see org.springframework.util.SystemPropertyUtils#PLACEHOLDER_PREFIX */ @Override public void setPlaceholderPrefix(String placeholderPrefix) { this.placeholderPrefix = placeholderPrefix; } /** * Set the suffix that placeholders replaced by this resolver must end with. * <p> * The default is "}". * * @see org.springframework.util.SystemPropertyUtils#PLACEHOLDER_SUFFIX */ @Override public void setPlaceholderSuffix(String placeholderSuffix) { this.placeholderSuffix = placeholderSuffix; } /** * Specify the separating character between the placeholders replaced by this * resolver and their associated default value, or {@code null} if no such * special character should be processed as a value separator. * <p> * The default is ":". * * @see org.springframework.util.SystemPropertyUtils#VALUE_SEPARATOR */ @Override public void setValueSeparator(String valueSeparator) { this.valueSeparator = valueSeparator; } /** * Set whether to throw an exception when encountering an unresolvable * placeholder nested within the value of a given property. A {@code false} * value indicates strict resolution, i.e. that an exception will be thrown. A * {@code true} value indicates that unresolvable nested placeholders should be * passed through in their unresolved ${...} form. * <p> * The default is {@code false}. * * @since 3.2 */ @Override public void setIgnoreUnresolvableNestedPlaceholders(boolean ignoreUnresolvableNestedPlaceholders) { this.ignoreUnresolvableNestedPlaceholders = ignoreUnresolvableNestedPlaceholders; } @Override public void setRequiredProperties(String... requiredProperties) { this.requiredProperties.addAll(Arrays.asList(requiredProperties)); } @Override public void validateRequiredProperties() { MissingRequiredPropertiesException ex = new MissingRequiredPropertiesException(); for (String key : this.requiredProperties) { if (this.getProperty(key) == null) { ex.addMissingRequiredProperty(key); } } if (!ex.getMissingRequiredProperties().isEmpty()) { throw ex; } } @Override public boolean containsProperty(String key) { return (getProperty(key) != null); } @Override public String getProperty(String key) { return getProperty(key, String.class); } @Override public String getProperty(String key, String defaultValue) { String value = getProperty(key); return (value != null ? value : defaultValue); } @Override public <T> T getProperty(String key, Class<T> targetType, T defaultValue) { T value = getProperty(key, targetType); return (value != null ? value : defaultValue); } @Override public String getRequiredProperty(String key) throws IllegalStateException { String value = getProperty(key); if (value == null) { throw new IllegalStateException("Required key '" + key + "' not found"); } return value; } @Override public <T> T getRequiredProperty(String key, Class<T> valueType) throws IllegalStateException { T value = getProperty(key, valueType); if (value == null) { throw new IllegalStateException("Required key '" + key + "' not found"); } return value; } @Override public String resolvePlaceholders(String text) { if (this.nonStrictHelper == null) { this.nonStrictHelper = createPlaceholderHelper(true); } return doResolvePlaceholders(text, this.nonStrictHelper); } @Override public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException { if (this.strictHelper == null) { this.strictHelper = createPlaceholderHelper(false); } return doResolvePlaceholders(text, this.strictHelper); } /** * Resolve placeholders within the given string, deferring to the value of * {@link #setIgnoreUnresolvableNestedPlaceholders} to determine whether any * unresolvable placeholders should raise an exception or be ignored. * <p> * Invoked from {@link #getProperty} and its variants, implicitly resolving * nested placeholders. In contrast, {@link #resolvePlaceholders} and * {@link #resolveRequiredPlaceholders} do <i>not</i> delegate to this method * but rather perform their own handling of unresolvable placeholders, as * specified by each of those methods. * * @since 3.2 * @see #setIgnoreUnresolvableNestedPlaceholders */ protected String resolveNestedPlaceholders(String value) { return (this.ignoreUnresolvableNestedPlaceholders ? resolvePlaceholders(value) : resolveRequiredPlaceholders(value)); } private PropertyPlaceholderHelper createPlaceholderHelper(boolean ignoreUnresolvablePlaceholders) { return new PropertyPlaceholderHelper(this.placeholderPrefix, this.placeholderSuffix, this.valueSeparator, ignoreUnresolvablePlaceholders); } private String doResolvePlaceholders(String text, PropertyPlaceholderHelper helper) { return helper.replacePlaceholders(text, new PropertyPlaceholderHelper.PlaceholderResolver() { public String resolvePlaceholder(String placeholderName) { return getPropertyAsRawString(placeholderName); } }); } /** * Retrieve the specified property as a raw String, i.e. without resolution of * nested placeholders. * * @param key the property name to resolve * @return the property value or {@code null} if none found */ protected abstract String getPropertyAsRawString(String key); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/package-info.java
core/src/main/java/com/taobao/arthas/core/env/package-info.java
/** * from org.springframework.core.env */ package com.taobao.arthas.core.env;
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/ArthasEnvironment.java
core/src/main/java/com/taobao/arthas/core/env/ArthasEnvironment.java
package com.taobao.arthas.core.env; import java.security.AccessControlException; import java.util.Map; /** * * @author hengyunabc 2019-12-27 * */ public class ArthasEnvironment implements Environment { /** System environment property source name: {@value}. */ public static final String SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME = "systemEnvironment"; /** JVM system properties property source name: {@value}. */ public static final String SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME = "systemProperties"; private final MutablePropertySources propertySources = new MutablePropertySources(); private final ConfigurablePropertyResolver propertyResolver = new PropertySourcesPropertyResolver( this.propertySources); public ArthasEnvironment() { propertySources.addLast( new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment())); propertySources .addLast(new PropertiesPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties())); } /** * Add the given property source object with highest precedence. */ public void addFirst(PropertySource<?> propertySource) { this.propertySources.addFirst(propertySource); } /** * Add the given property source object with lowest precedence. */ public void addLast(PropertySource<?> propertySource) { this.propertySources.addLast(propertySource); } @SuppressWarnings({ "rawtypes", "unchecked" }) public Map<String, Object> getSystemProperties() { try { return (Map) System.getProperties(); } catch (AccessControlException ex) { return (Map) new ReadOnlySystemAttributesMap() { @Override protected String getSystemAttribute(String attributeName) { try { return System.getProperty(attributeName); } catch (AccessControlException ex) { return null; } } }; } } @SuppressWarnings({ "rawtypes", "unchecked" }) public Map<String, Object> getSystemEnvironment() { try { return (Map) System.getenv(); } catch (AccessControlException ex) { return (Map) new ReadOnlySystemAttributesMap() { @Override protected String getSystemAttribute(String attributeName) { try { return System.getenv(attributeName); } catch (AccessControlException ex) { return null; } } }; } } // --------------------------------------------------------------------- // Implementation of PropertyResolver interface // --------------------------------------------------------------------- @Override public boolean containsProperty(String key) { return this.propertyResolver.containsProperty(key); } @Override public String getProperty(String key) { return this.propertyResolver.getProperty(key); } @Override public String getProperty(String key, String defaultValue) { return this.propertyResolver.getProperty(key, defaultValue); } @Override public <T> T getProperty(String key, Class<T> targetType) { return this.propertyResolver.getProperty(key, targetType); } @Override public <T> T getProperty(String key, Class<T> targetType, T defaultValue) { return this.propertyResolver.getProperty(key, targetType, defaultValue); } @Override public String getRequiredProperty(String key) throws IllegalStateException { return this.propertyResolver.getRequiredProperty(key); } @Override public <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException { return this.propertyResolver.getRequiredProperty(key, targetType); } @Override public String resolvePlaceholders(String text) { return this.propertyResolver.resolvePlaceholders(text); } @Override public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException { return this.propertyResolver.resolveRequiredPlaceholders(text); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/ConfigurablePropertyResolver.java
core/src/main/java/com/taobao/arthas/core/env/ConfigurablePropertyResolver.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; import com.taobao.arthas.core.env.convert.ConfigurableConversionService; /** * Configuration interface to be implemented by most if not all * {@link PropertyResolver} types. Provides facilities for accessing and * customizing the {@link org.springframework.core.convert.ConversionService * ConversionService} used when converting property values from one type to * another. * * @author Chris Beams * @since 3.1 */ public interface ConfigurablePropertyResolver extends PropertyResolver { /** * Return the {@link ConfigurableConversionService} used when performing type * conversions on properties. * <p> * The configurable nature of the returned conversion service allows for the * convenient addition and removal of individual {@code Converter} instances: * * <pre class="code"> * ConfigurableConversionService cs = env.getConversionService(); * cs.addConverter(new FooConverter()); * </pre> * * @see PropertyResolver#getProperty(String, Class) * @see org.springframework.core.convert.converter.ConverterRegistry#addConverter */ ConfigurableConversionService getConversionService(); /** * Set the {@link ConfigurableConversionService} to be used when performing type * conversions on properties. * <p> * <strong>Note:</strong> as an alternative to fully replacing the * {@code ConversionService}, consider adding or removing individual * {@code Converter} instances by drilling into {@link #getConversionService()} * and calling methods such as {@code #addConverter}. * * @see PropertyResolver#getProperty(String, Class) * @see #getConversionService() * @see org.springframework.core.convert.converter.ConverterRegistry#addConverter */ void setConversionService(ConfigurableConversionService conversionService); /** * Set the prefix that placeholders replaced by this resolver must begin with. */ void setPlaceholderPrefix(String placeholderPrefix); /** * Set the suffix that placeholders replaced by this resolver must end with. */ void setPlaceholderSuffix(String placeholderSuffix); /** * Specify the separating character between the placeholders replaced by this * resolver and their associated default value, or {@code null} if no such * special character should be processed as a value separator. */ void setValueSeparator(String valueSeparator); /** * Set whether to throw an exception when encountering an unresolvable * placeholder nested within the value of a given property. A {@code false} * value indicates strict resolution, i.e. that an exception will be thrown. A * {@code true} value indicates that unresolvable nested placeholders should be * passed through in their unresolved ${...} form. * <p> * Implementations of {@link #getProperty(String)} and its variants must inspect * the value set here to determine correct behavior when property values contain * unresolvable placeholders. * * @since 3.2 */ void setIgnoreUnresolvableNestedPlaceholders(boolean ignoreUnresolvableNestedPlaceholders); /** * Specify which properties must be present, to be verified by * {@link #validateRequiredProperties()}. */ void setRequiredProperties(String... requiredProperties); /** * Validate that each of the properties specified by * {@link #setRequiredProperties} is present and resolves to a non-{@code null} * value. * * @throws MissingRequiredPropertiesException if any of the required properties * are not resolvable. */ void validateRequiredProperties() throws MissingRequiredPropertiesException; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/SystemPropertyUtils.java
core/src/main/java/com/taobao/arthas/core/env/SystemPropertyUtils.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; /** * Helper class for resolving placeholders in texts. Usually applied to file * paths. * * <p> * A text may contain {@code ${...}} placeholders, to be resolved as system * properties: e.g. {@code ${user.dir}}. Default values can be supplied using * the ":" separator between key and value. * * @author Juergen Hoeller * @author Rob Harrop * @author Dave Syer * @since 1.2.5 * @see #PLACEHOLDER_PREFIX * @see #PLACEHOLDER_SUFFIX * @see System#getProperty(String) */ public abstract class SystemPropertyUtils { /** Prefix for system property placeholders: "${". */ public static final String PLACEHOLDER_PREFIX = "${"; /** Suffix for system property placeholders: "}". */ public static final String PLACEHOLDER_SUFFIX = "}"; /** Value separator for system property placeholders: ":". */ public static final String VALUE_SEPARATOR = ":"; private static final PropertyPlaceholderHelper strictHelper = new PropertyPlaceholderHelper(PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, VALUE_SEPARATOR, false); private static final PropertyPlaceholderHelper nonStrictHelper = new PropertyPlaceholderHelper(PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, VALUE_SEPARATOR, true); /** * Resolve {@code ${...}} placeholders in the given text, replacing them with * corresponding system property values. * * @param text the String to resolve * @return the resolved String * @throws IllegalArgumentException if there is an unresolvable placeholder * @see #PLACEHOLDER_PREFIX * @see #PLACEHOLDER_SUFFIX */ public static String resolvePlaceholders(String text) { return resolvePlaceholders(text, false); } /** * Resolve {@code ${...}} placeholders in the given text, replacing them with * corresponding system property values. Unresolvable placeholders with no * default value are ignored and passed through unchanged if the flag is set to * {@code true}. * * @param text the String to resolve * @param ignoreUnresolvablePlaceholders whether unresolved placeholders are to * be ignored * @return the resolved String * @throws IllegalArgumentException if there is an unresolvable placeholder * @see #PLACEHOLDER_PREFIX * @see #PLACEHOLDER_SUFFIX and the "ignoreUnresolvablePlaceholders" flag is * {@code false} */ public static String resolvePlaceholders(String text, boolean ignoreUnresolvablePlaceholders) { PropertyPlaceholderHelper helper = (ignoreUnresolvablePlaceholders ? nonStrictHelper : strictHelper); return helper.replacePlaceholders(text, new SystemPropertyPlaceholderResolver(text)); } /** * PlaceholderResolver implementation that resolves against system properties * and system environment variables. */ private static class SystemPropertyPlaceholderResolver implements PropertyPlaceholderHelper.PlaceholderResolver { private final String text; public SystemPropertyPlaceholderResolver(String text) { this.text = text; } @Override public String resolvePlaceholder(String placeholderName) { try { String propVal = System.getProperty(placeholderName); if (propVal == null) { // Fall back to searching the system environment. propVal = System.getenv(placeholderName); } return propVal; } catch (Throwable ex) { System.err.println("Could not resolve placeholder '" + placeholderName + "' in [" + this.text + "] as system property: " + ex); return null; } } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/PropertyPlaceholderHelper.java
core/src/main/java/com/taobao/arthas/core/env/PropertyPlaceholderHelper.java
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; /** * Utility class for working with Strings that have placeholder values in them. * A placeholder takes the form {@code ${name}}. Using * {@code PropertyPlaceholderHelper} these placeholders can be substituted for * user-supplied values. * <p> * Values for substitution can be supplied using a {@link Properties} instance * or using a {@link PlaceholderResolver}. * * @author Juergen Hoeller * @author Rob Harrop * @since 3.0 */ public class PropertyPlaceholderHelper { private static final Map<String, String> wellKnownSimplePrefixes = new HashMap<String, String>(4); static { wellKnownSimplePrefixes.put("}", "{"); wellKnownSimplePrefixes.put("]", "["); wellKnownSimplePrefixes.put(")", "("); } private final String placeholderPrefix; private final String placeholderSuffix; private final String simplePrefix; private final String valueSeparator; private final boolean ignoreUnresolvablePlaceholders; /** * Creates a new {@code PropertyPlaceholderHelper} that uses the supplied prefix * and suffix. Unresolvable placeholders are ignored. * * @param placeholderPrefix the prefix that denotes the start of a placeholder * @param placeholderSuffix the suffix that denotes the end of a placeholder */ public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix) { this(placeholderPrefix, placeholderSuffix, null, true); } /** * Creates a new {@code PropertyPlaceholderHelper} that uses the supplied prefix * and suffix. * * @param placeholderPrefix the prefix that denotes the start of a * placeholder * @param placeholderSuffix the suffix that denotes the end of a * placeholder * @param valueSeparator the separating character between the * placeholder variable and the associated * default value, if any * @param ignoreUnresolvablePlaceholders indicates whether unresolvable * placeholders should be ignored * ({@code true}) or cause an exception * ({@code false}) */ public PropertyPlaceholderHelper(String placeholderPrefix, String placeholderSuffix, String valueSeparator, boolean ignoreUnresolvablePlaceholders) { this.placeholderPrefix = placeholderPrefix; this.placeholderSuffix = placeholderSuffix; String simplePrefixForSuffix = wellKnownSimplePrefixes.get(this.placeholderSuffix); if (simplePrefixForSuffix != null && this.placeholderPrefix.endsWith(simplePrefixForSuffix)) { this.simplePrefix = simplePrefixForSuffix; } else { this.simplePrefix = this.placeholderPrefix; } this.valueSeparator = valueSeparator; this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders; } /** * Replaces all placeholders of format {@code ${name}} with the corresponding * property from the supplied {@link Properties}. * * @param value the value containing the placeholders to be replaced * @param properties the {@code Properties} to use for replacement * @return the supplied value with placeholders replaced inline */ public String replacePlaceholders(String value, final Properties properties) { return replacePlaceholders(value, new PlaceholderResolver() { public String resolvePlaceholder(String placeholderName) { return properties.getProperty(placeholderName); } }); } /** * Replaces all placeholders of format {@code ${name}} with the value returned * from the supplied {@link PlaceholderResolver}. * * @param value the value containing the placeholders to be * replaced * @param placeholderResolver the {@code PlaceholderResolver} to use for * replacement * @return the supplied value with placeholders replaced inline */ public String replacePlaceholders(String value, PlaceholderResolver placeholderResolver) { return parseStringValue(value, placeholderResolver, null); } protected String parseStringValue(String value, PlaceholderResolver placeholderResolver, Set<String> visitedPlaceholders) { int startIndex = value.indexOf(this.placeholderPrefix); if (startIndex == -1) { return value; } StringBuilder result = new StringBuilder(value); while (startIndex != -1) { int endIndex = findPlaceholderEndIndex(result, startIndex); if (endIndex != -1) { String placeholder = result.substring(startIndex + this.placeholderPrefix.length(), endIndex); String originalPlaceholder = placeholder; if (visitedPlaceholders == null) { visitedPlaceholders = new HashSet<String>(4); } if (!visitedPlaceholders.add(originalPlaceholder)) { throw new IllegalArgumentException( "Circular placeholder reference '" + originalPlaceholder + "' in property definitions"); } // Recursive invocation, parsing placeholders contained in the placeholder key. placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders); // Now obtain the value for the fully resolved key... String propVal = placeholderResolver.resolvePlaceholder(placeholder); if (propVal == null && this.valueSeparator != null) { int separatorIndex = placeholder.indexOf(this.valueSeparator); if (separatorIndex != -1) { String actualPlaceholder = placeholder.substring(0, separatorIndex); String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length()); propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder); if (propVal == null) { propVal = defaultValue; } } } if (propVal != null) { // Recursive invocation, parsing placeholders contained in the // previously resolved placeholder value. propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders); result.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal); startIndex = result.indexOf(this.placeholderPrefix, startIndex + propVal.length()); } else if (this.ignoreUnresolvablePlaceholders) { // Proceed with unprocessed value. startIndex = result.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length()); } else { throw new IllegalArgumentException( "Could not resolve placeholder '" + placeholder + "'" + " in value \"" + value + "\""); } visitedPlaceholders.remove(originalPlaceholder); } else { startIndex = -1; } } return result.toString(); } private int findPlaceholderEndIndex(CharSequence buf, int startIndex) { int index = startIndex + this.placeholderPrefix.length(); int withinNestedPlaceholder = 0; while (index < buf.length()) { if (substringMatch(buf, index, this.placeholderSuffix)) { if (withinNestedPlaceholder > 0) { withinNestedPlaceholder--; index = index + this.placeholderSuffix.length(); } else { return index; } } else if (substringMatch(buf, index, this.simplePrefix)) { withinNestedPlaceholder++; index = index + this.simplePrefix.length(); } else { index++; } } return -1; } /** * Test whether the given string matches the given substring at the given index. * * @param str the original string (or StringBuilder) * @param index the index in the original string to start matching against * @param substring the substring to match at the given index */ public static boolean substringMatch(CharSequence str, int index, CharSequence substring) { if (index + substring.length() > str.length()) { return false; } for (int i = 0; i < substring.length(); i++) { if (str.charAt(index + i) != substring.charAt(i)) { return false; } } return true; } /** * Strategy interface used to resolve replacement values for placeholders * contained in Strings. */ public interface PlaceholderResolver { /** * Resolve the supplied placeholder name to the replacement value. * * @param placeholderName the name of the placeholder to resolve * @return the replacement value, or {@code null} if no replacement is to be * made */ String resolvePlaceholder(String placeholderName); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
core/src/main/java/com/taobao/arthas/core/env/MutablePropertySources.java
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; import java.util.Iterator; import java.util.LinkedList; /** * Default implementation of the {@link PropertySources} interface. Allows * manipulation of contained property sources and provides a constructor for * copying an existing {@code PropertySources} instance. * * <p> * Where <em>precedence</em> is mentioned in methods such as {@link #addFirst} * and {@link #addLast}, this is with regard to the order in which property * sources will be searched when resolving a given property with a * {@link PropertyResolver}. * * @author Chris Beams * @since 3.1 * @see PropertySourcesPropertyResolver */ public class MutablePropertySources implements PropertySources { static final String NON_EXISTENT_PROPERTY_SOURCE_MESSAGE = "PropertySource named [%s] does not exist"; static final String ILLEGAL_RELATIVE_ADDITION_MESSAGE = "PropertySource named [%s] cannot be added relative to itself"; private final LinkedList<PropertySource<?>> propertySourceList = new LinkedList<PropertySource<?>>(); /** * Create a new {@link MutablePropertySources} object. */ public MutablePropertySources() { } /** * Create a new {@code MutablePropertySources} from the given propertySources * object, preserving the original order of contained {@code PropertySource} * objects. */ public MutablePropertySources(PropertySources propertySources) { this(); for (PropertySource<?> propertySource : propertySources) { this.addLast(propertySource); } } public boolean contains(String name) { return this.propertySourceList.contains(PropertySource.named(name)); } public PropertySource<?> get(String name) { int index = this.propertySourceList.indexOf(PropertySource.named(name)); return index == -1 ? null : this.propertySourceList.get(index); } public Iterator<PropertySource<?>> iterator() { return this.propertySourceList.iterator(); } /** * Add the given property source object with highest precedence. */ public void addFirst(PropertySource<?> propertySource) { // if (logger.isDebugEnabled()) { // logger.debug(String.format("Adding [%s] PropertySource with highest search precedence", // propertySource.getName())); // } removeIfPresent(propertySource); this.propertySourceList.addFirst(propertySource); } /** * Add the given property source object with lowest precedence. */ public void addLast(PropertySource<?> propertySource) { // if (logger.isDebugEnabled()) { // logger.debug(String.format("Adding [%s] PropertySource with lowest search precedence", // propertySource.getName())); // } removeIfPresent(propertySource); this.propertySourceList.addLast(propertySource); } /** * Add the given property source object with precedence immediately higher than * the named relative property source. */ public void addBefore(String relativePropertySourceName, PropertySource<?> propertySource) { // if (logger.isDebugEnabled()) { // logger.debug(String.format("Adding [%s] PropertySource with search precedence immediately higher than [%s]", // propertySource.getName(), relativePropertySourceName)); // } assertLegalRelativeAddition(relativePropertySourceName, propertySource); removeIfPresent(propertySource); int index = assertPresentAndGetIndex(relativePropertySourceName); addAtIndex(index, propertySource); } /** * Add the given property source object with precedence immediately lower than * the named relative property source. */ public void addAfter(String relativePropertySourceName, PropertySource<?> propertySource) { // if (logger.isDebugEnabled()) { // logger.debug(String.format("Adding [%s] PropertySource with search precedence immediately lower than [%s]", // propertySource.getName(), relativePropertySourceName)); // } assertLegalRelativeAddition(relativePropertySourceName, propertySource); removeIfPresent(propertySource); int index = assertPresentAndGetIndex(relativePropertySourceName); addAtIndex(index + 1, propertySource); } /** * Return the precedence of the given property source, {@code -1} if not found. */ public int precedenceOf(PropertySource<?> propertySource) { return this.propertySourceList.indexOf(propertySource); } /** * Remove and return the property source with the given name, {@code null} if * not found. * * @param name the name of the property source to find and remove */ public PropertySource<?> remove(String name) { // if (logger.isDebugEnabled()) { // logger.debug(String.format("Removing [%s] PropertySource", name)); // } int index = this.propertySourceList.indexOf(PropertySource.named(name)); return index == -1 ? null : this.propertySourceList.remove(index); } /** * Replace the property source with the given name with the given property * source object. * * @param name the name of the property source to find and replace * @param propertySource the replacement property source * @throws IllegalArgumentException if no property source with the given name is * present * @see #contains */ public void replace(String name, PropertySource<?> propertySource) { // if (logger.isDebugEnabled()) { // logger.debug(String.format("Replacing [%s] PropertySource with [%s]", // name, propertySource.getName())); // } int index = assertPresentAndGetIndex(name); this.propertySourceList.set(index, propertySource); } /** * Return the number of {@link PropertySource} objects contained. */ public int size() { return this.propertySourceList.size(); } @Override public String toString() { String[] names = new String[this.size()]; for (int i = 0; i < size(); i++) { names[i] = this.propertySourceList.get(i).getName(); } return String.format("[%s]", arrayToCommaDelimitedString(names)); } /** * Ensure that the given property source is not being added relative to itself. */ protected void assertLegalRelativeAddition(String relativePropertySourceName, PropertySource<?> propertySource) { // String newPropertySourceName = propertySource.getName(); // Assert.isTrue(!relativePropertySourceName.equals(newPropertySourceName), // String.format(ILLEGAL_RELATIVE_ADDITION_MESSAGE, newPropertySourceName)); } /** * Remove the given property source if it is present. */ protected void removeIfPresent(PropertySource<?> propertySource) { this.propertySourceList.remove(propertySource); } /** * Add the given property source at a particular index in the list. */ private void addAtIndex(int index, PropertySource<?> propertySource) { removeIfPresent(propertySource); this.propertySourceList.add(index, propertySource); } /** * Assert that the named property source is present and return its index. * * @param name the {@linkplain PropertySource#getName() name of the property * source} to find * @throws IllegalArgumentException if the named property source is not present */ private int assertPresentAndGetIndex(String name) { int index = this.propertySourceList.indexOf(PropertySource.named(name)); // Assert.isTrue(index >= 0, String.format(NON_EXISTENT_PROPERTY_SOURCE_MESSAGE, name)); return index; } /** * Convenience method to return a String array as a delimited (e.g. CSV) String. * E.g. useful for {@code toString()} implementations. * * @param arr the array to display * @param delim the delimiter to use (probably a ",") * @return the delimited String */ private static String arrayToDelimitedString(Object[] arr, String delim) { if (arr == null || arr.length == 0) { return ""; } if (arr.length == 1) { return nullSafeToString(arr[0]); } StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { if (i > 0) { sb.append(delim); } sb.append(arr[i]); } return sb.toString(); } /** * Return a String representation of the specified Object. * <p> * Builds a String representation of the contents in case of an array. Returns * {@code "null"} if {@code obj} is {@code null}. * * @param obj the object to build a String representation for * @return a String representation of {@code obj} */ private static String nullSafeToString(Object obj) { if (obj == null) { return "null"; } if (obj instanceof String) { return (String) obj; } if (obj instanceof Object[]) { return nullSafeToString((Object[]) obj); } if (obj instanceof boolean[]) { return nullSafeToString((boolean[]) obj); } if (obj instanceof byte[]) { return nullSafeToString((byte[]) obj); } if (obj instanceof char[]) { return nullSafeToString((char[]) obj); } if (obj instanceof double[]) { return nullSafeToString((double[]) obj); } if (obj instanceof float[]) { return nullSafeToString((float[]) obj); } if (obj instanceof int[]) { return nullSafeToString((int[]) obj); } if (obj instanceof long[]) { return nullSafeToString((long[]) obj); } if (obj instanceof short[]) { return nullSafeToString((short[]) obj); } String str = obj.toString(); return (str != null ? str : ""); } /** * Convenience method to return a String array as a CSV String. E.g. useful for * {@code toString()} implementations. * * @param arr the array to display * @return the delimited String */ private static String arrayToCommaDelimitedString(Object[] arr) { return arrayToDelimitedString(arr, ","); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/EnumerablePropertySource.java
core/src/main/java/com/taobao/arthas/core/env/EnumerablePropertySource.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; /** * A {@link PropertySource} implementation capable of interrogating its * underlying source object to enumerate all possible property name/value pairs. * Exposes the {@link #getPropertyNames()} method to allow callers to introspect * available properties without having to access the underlying source object. * This also facilitates a more efficient implementation of * {@link #containsProperty(String)}, in that it can call * {@link #getPropertyNames()} and iterate through the returned array rather * than attempting a call to {@link #getProperty(String)} which may be more * expensive. Implementations may consider caching the result of * {@link #getPropertyNames()} to fully exploit this performance opportunity. * * <p> * Most framework-provided {@code PropertySource} implementations are * enumerable; a counter-example would be {@code JndiPropertySource} where, due * to the nature of JNDI it is not possible to determine all possible property * names at any given time; rather it is only possible to try to access a * property (via {@link #getProperty(String)}) in order to evaluate whether it * is present or not. * * @author Chris Beams * @author Juergen Hoeller * @since 3.1 * @param <T> the source type */ public abstract class EnumerablePropertySource<T> extends PropertySource<T> { public EnumerablePropertySource(String name, T source) { super(name, source); } protected EnumerablePropertySource(String name) { super(name); } /** * Return whether this {@code PropertySource} contains a property with the given * name. * <p> * This implementation checks for the presence of the given name within the * {@link #getPropertyNames()} array. * * @param name the name of the property to find */ @Override public boolean containsProperty(String name) { String[] propertyNames = getPropertyNames(); if (propertyNames == null) { return false; } for (String temp : propertyNames) { if (temp.equals(name)) { return true; } } return false; } /** * Return the names of all properties contained by the {@linkplain #getSource() * source} object (never {@code null}). */ public abstract String[] getPropertyNames(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/ReadOnlySystemAttributesMap.java
core/src/main/java/com/taobao/arthas/core/env/ReadOnlySystemAttributesMap.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; /** * Read-only {@code Map<String, String>} implementation that is backed by system * properties or environment variables. * * <p> * Used by {@link AbstractApplicationContext} when a {@link SecurityManager} * prohibits access to {@link System#getProperties()} or * {@link System#getenv()}. It is for this reason that the implementations of * {@link #keySet()}, {@link #entrySet()}, and {@link #values()} always return * empty even though {@link #get(Object)} may in fact return non-null if the * current security manager allows access to individual keys. * * @author Arjen Poutsma * @author Chris Beams * @since 3.0 */ abstract class ReadOnlySystemAttributesMap implements Map<String, String> { @Override public boolean containsKey(Object key) { return (get(key) != null); } /** * Returns the value to which the specified key is mapped, or {@code null} if * this map contains no mapping for the key. * * @param key the name of the system attribute to retrieve * @throws IllegalArgumentException if given key is non-String */ @Override public String get(Object key) { if (!(key instanceof String)) { throw new IllegalArgumentException( "Type of key [" + key.getClass().getName() + "] must be java.lang.String"); } return getSystemAttribute((String) key); } @Override public boolean isEmpty() { return false; } /** * Template method that returns the underlying system attribute. * <p> * Implementations typically call {@link System#getProperty(String)} or * {@link System#getenv(String)} here. */ protected abstract String getSystemAttribute(String attributeName); // Unsupported @Override public int size() { throw new UnsupportedOperationException(); } @Override public String put(String key, String value) { throw new UnsupportedOperationException(); } @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } @Override public String remove(Object key) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Set<String> keySet() { return Collections.emptySet(); } @Override public void putAll(Map<? extends String, ? extends String> map) { throw new UnsupportedOperationException(); } @Override public Collection<String> values() { return Collections.emptySet(); } @Override public Set<Entry<String, String>> entrySet() { return Collections.emptySet(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/PropertiesPropertySource.java
core/src/main/java/com/taobao/arthas/core/env/PropertiesPropertySource.java
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; import java.util.Map; import java.util.Properties; /** * {@link PropertySource} implementation that extracts properties from a * {@link java.util.Properties} object. * * <p> * Note that because a {@code Properties} object is technically an * {@code <Object, Object>} {@link java.util.Hashtable Hashtable}, one may * contain non-{@code String} keys or values. This implementation, however is * restricted to accessing only {@code String}-based keys and values, in the * same fashion as {@link Properties#getProperty} and * {@link Properties#setProperty}. * * @author Chris Beams * @author Juergen Hoeller * @since 3.1 */ public class PropertiesPropertySource extends MapPropertySource { @SuppressWarnings({ "rawtypes", "unchecked" }) public PropertiesPropertySource(String name, Properties source) { super(name, (Map) source); } protected PropertiesPropertySource(String name, Map<String, Object> source) { super(name, source); } @Override public String[] getPropertyNames() { synchronized (this.source) { return super.getPropertyNames(); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/Environment.java
core/src/main/java/com/taobao/arthas/core/env/Environment.java
package com.taobao.arthas.core.env; public interface Environment extends PropertyResolver { }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/PropertySource.java
core/src/main/java/com/taobao/arthas/core/env/PropertySource.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; import java.util.Arrays; /** * Abstract base class representing a source of name/value property pairs. The * underlying {@linkplain #getSource() source object} may be of any type * {@code T} that encapsulates properties. Examples include * {@link java.util.Properties} objects, {@link java.util.Map} objects, * {@code ServletContext} and {@code ServletConfig} objects (for access to init * parameters). Explore the {@code PropertySource} type hierarchy to see * provided implementations. * * <p> * {@code PropertySource} objects are not typically used in isolation, but * rather through a {@link PropertySources} object, which aggregates property * sources and in conjunction with a {@link PropertyResolver} implementation * that can perform precedence-based searches across the set of * {@code PropertySources}. * * <p> * {@code PropertySource} identity is determined not based on the content of * encapsulated properties, but rather based on the {@link #getName() name} of * the {@code PropertySource} alone. This is useful for manipulating * {@code PropertySource} objects when in collection contexts. See operations in * {@link MutablePropertySources} as well as the {@link #named(String)} and * {@link #toString()} methods for details. * * <p> * Note that when working * with @{@link org.springframework.context.annotation.Configuration * Configuration} classes that * the @{@link org.springframework.context.annotation.PropertySource * PropertySource} annotation provides a convenient and declarative way of * adding property sources to the enclosing {@code Environment}. * * @author Chris Beams * @since 3.1 * @param <T> the source type * @see PropertySources * @see PropertyResolver * @see PropertySourcesPropertyResolver * @see MutablePropertySources * @see org.springframework.context.annotation.PropertySource */ public abstract class PropertySource<T> { protected final String name; protected final T source; /** * Create a new {@code PropertySource} with the given name and source object. */ public PropertySource(String name, T source) { this.name = name; this.source = source; } /** * Create a new {@code PropertySource} with the given name and with a new * {@code Object} instance as the underlying source. * <p> * Often useful in testing scenarios when creating anonymous implementations * that never query an actual source but rather return hard-coded values. */ @SuppressWarnings("unchecked") public PropertySource(String name) { this(name, (T) new Object()); } /** * Return the name of this {@code PropertySource}. */ public String getName() { return this.name; } /** * Return the underlying source object for this {@code PropertySource}. */ public T getSource() { return this.source; } /** * Return whether this {@code PropertySource} contains the given name. * <p> * This implementation simply checks for a {@code null} return value from * {@link #getProperty(String)}. Subclasses may wish to implement a more * efficient algorithm if possible. * * @param name the property name to find */ public boolean containsProperty(String name) { return (getProperty(name) != null); } /** * Return the value associated with the given name, or {@code null} if not * found. * * @param name the property to find * @see PropertyResolver#getRequiredProperty(String) */ public abstract Object getProperty(String name); /** * This {@code PropertySource} object is equal to the given object if: * <ul> * <li>they are the same instance * <li>the {@code name} properties for both objects are equal * </ul> * <p> * No properties other than {@code name} are evaluated. */ @Override public boolean equals(Object other) { return (this == other || (other instanceof PropertySource && nullSafeEquals(this.name, ((PropertySource<?>) other).name))); } /** * Return a hash code derived from the {@code name} property of this * {@code PropertySource} object. */ @Override public int hashCode() { return this.name.hashCode(); } /** * Produce concise output (type and name) if the current log level does not * include debug. If debug is enabled, produce verbose output including the hash * code of the PropertySource instance and every name/value property pair. * <p> * This variable verbosity is useful as a property source such as system * properties or environment variables may contain an arbitrary number of * property pairs, potentially leading to difficult to read exception and log * messages. * * @see Log#isDebugEnabled() */ @Override public String toString() { return getClass().getSimpleName() + " {name='" + this.name + "'}"; } /** * Return a {@code PropertySource} implementation intended for collection * comparison purposes only. * <p> * Primarily for internal use, but given a collection of {@code PropertySource} * objects, may be used as follows: * * <pre class="code"> * { * &#64;code * List<PropertySource<?>> sources = new ArrayList<PropertySource<?>>(); * sources.add(new MapPropertySource("sourceA", mapA)); * sources.add(new MapPropertySource("sourceB", mapB)); * assert sources.contains(PropertySource.named("sourceA")); * assert sources.contains(PropertySource.named("sourceB")); * assert !sources.contains(PropertySource.named("sourceC")); * } * </pre> * * The returned {@code PropertySource} will throw * {@code UnsupportedOperationException} if any methods other than * {@code equals(Object)}, {@code hashCode()}, and {@code toString()} are * called. * * @param name the name of the comparison {@code PropertySource} to be created * and returned. */ public static PropertySource<?> named(String name) { return new ComparisonPropertySource(name); } /** * Determine if the given objects are equal, returning {@code true} if both are * {@code null} or {@code false} if only one is {@code null}. * <p> * Compares arrays with {@code Arrays.equals}, performing an equality check * based on the array elements rather than the array reference. * * @param o1 first Object to compare * @param o2 second Object to compare * @return whether the given objects are equal * @see Object#equals(Object) * @see java.util.Arrays#equals */ public static boolean nullSafeEquals(Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } if (o1.equals(o2)) { return true; } if (o1.getClass().isArray() && o2.getClass().isArray()) { return arrayEquals(o1, o2); } return false; } /** * Compare the given arrays with {@code Arrays.equals}, performing an equality * check based on the array elements rather than the array reference. * * @param o1 first array to compare * @param o2 second array to compare * @return whether the given objects are equal * @see #nullSafeEquals(Object, Object) * @see java.util.Arrays#equals */ private static boolean arrayEquals(Object o1, Object o2) { if (o1 instanceof Object[] && o2 instanceof Object[]) { return Arrays.equals((Object[]) o1, (Object[]) o2); } if (o1 instanceof boolean[] && o2 instanceof boolean[]) { return Arrays.equals((boolean[]) o1, (boolean[]) o2); } if (o1 instanceof byte[] && o2 instanceof byte[]) { return Arrays.equals((byte[]) o1, (byte[]) o2); } if (o1 instanceof char[] && o2 instanceof char[]) { return Arrays.equals((char[]) o1, (char[]) o2); } if (o1 instanceof double[] && o2 instanceof double[]) { return Arrays.equals((double[]) o1, (double[]) o2); } if (o1 instanceof float[] && o2 instanceof float[]) { return Arrays.equals((float[]) o1, (float[]) o2); } if (o1 instanceof int[] && o2 instanceof int[]) { return Arrays.equals((int[]) o1, (int[]) o2); } if (o1 instanceof long[] && o2 instanceof long[]) { return Arrays.equals((long[]) o1, (long[]) o2); } if (o1 instanceof short[] && o2 instanceof short[]) { return Arrays.equals((short[]) o1, (short[]) o2); } return false; } /** * {@code PropertySource} to be used as a placeholder in cases where an actual * property source cannot be eagerly initialized at application context creation * time. For example, a {@code ServletContext}-based property source must wait * until the {@code ServletContext} object is available to its enclosing * {@code ApplicationContext}. In such cases, a stub should be used to hold the * intended default position/order of the property source, then be replaced * during context refresh. * * @see org.springframework.context.support.AbstractApplicationContext#initPropertySources() * @see org.springframework.web.context.support.StandardServletEnvironment * @see org.springframework.web.context.support.ServletContextPropertySource */ public static class StubPropertySource extends PropertySource<Object> { public StubPropertySource(String name) { super(name, new Object()); } /** * Always returns {@code null}. */ @Override public String getProperty(String name) { return null; } } /** * @see PropertySource#named(String) */ static class ComparisonPropertySource extends StubPropertySource { private static final String USAGE_ERROR = "ComparisonPropertySource instances are for use with collection comparison only"; public ComparisonPropertySource(String name) { super(name); } @Override public Object getSource() { throw new UnsupportedOperationException(USAGE_ERROR); } @Override public boolean containsProperty(String name) { throw new UnsupportedOperationException(USAGE_ERROR); } @Override public String getProperty(String name) { throw new UnsupportedOperationException(USAGE_ERROR); } @Override public String toString() { return String.format("%s [name='%s']", getClass().getSimpleName(), this.name); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/PropertySourcesPropertyResolver.java
core/src/main/java/com/taobao/arthas/core/env/PropertySourcesPropertyResolver.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; /** * {@link PropertyResolver} implementation that resolves property values against * an underlying set of {@link PropertySources}. * * @author Chris Beams * @author Juergen Hoeller * @since 3.1 * @see PropertySource * @see PropertySources * @see AbstractEnvironment */ public class PropertySourcesPropertyResolver extends AbstractPropertyResolver { private final PropertySources propertySources; /** * Create a new resolver against the given property sources. * * @param propertySources the set of {@link PropertySource} objects to use */ public PropertySourcesPropertyResolver(PropertySources propertySources) { this.propertySources = propertySources; } @Override public boolean containsProperty(String key) { if (this.propertySources != null) { for (PropertySource<?> propertySource : this.propertySources) { if (propertySource.containsProperty(key)) { return true; } } } return false; } @Override public String getProperty(String key) { return getProperty(key, String.class, true); } @Override public <T> T getProperty(String key, Class<T> targetValueType) { return getProperty(key, targetValueType, true); } @Override protected String getPropertyAsRawString(String key) { return getProperty(key, String.class, false); } // protected <T> T getProperty(String key, Class<T> targetValueType, boolean resolveNestedPlaceholders) { // if (this.propertySources != null) { // for (PropertySource<?> propertySource : this.propertySources) { // Object value = propertySource.getProperty(key); // if (value != null) { // if (resolveNestedPlaceholders && value instanceof String) { // value = resolveNestedPlaceholders((String) value); // } // logKeyFound(key, propertySource, value); // return convertValueIfNecessary(value, targetValueType); // } // } // } // return null; // } protected <T> T getProperty(String key, Class<T> targetValueType, boolean resolveNestedPlaceholders) { if (this.propertySources != null) { for (PropertySource<?> propertySource : this.propertySources) { Object value; if ((value = propertySource.getProperty(key)) != null) { Class<?> valueType = value.getClass(); if (resolveNestedPlaceholders && value instanceof String) { value = resolveNestedPlaceholders((String) value); } if (!this.conversionService.canConvert(valueType, targetValueType)) { throw new IllegalArgumentException( String.format("Cannot convert value [%s] from source type [%s] to target type [%s]", value, valueType.getSimpleName(), targetValueType.getSimpleName())); } return this.conversionService.convert(value, targetValueType); } } } return null; } /** * Log the given key as found in the given {@link PropertySource}, resulting in * the given value. * <p> * The default implementation writes a debug log message with key and source. As * of 4.3.3, this does not log the value anymore in order to avoid accidental * logging of sensitive settings. Subclasses may override this method to change * the log level and/or log message, including the property's value if desired. * * @param key the key found * @param propertySource the {@code PropertySource} that the key has been found * in * @param value the corresponding value * @since 4.3.1 */ protected void logKeyFound(String key, PropertySource<?> propertySource, Object value) { // if (logger.isDebugEnabled()) { // logger.debug("Found key '" + key + "' in PropertySource '" + propertySource.getName() + // "' with value of type " + value.getClass().getSimpleName()); // } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/SystemEnvironmentPropertySource.java
core/src/main/java/com/taobao/arthas/core/env/SystemEnvironmentPropertySource.java
/* * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; import java.util.Map; /** * Specialization of {@link MapPropertySource} designed for use with * {@linkplain AbstractEnvironment#getSystemEnvironment() system environment * variables}. Compensates for constraints in Bash and other shells that do not * allow for variables containing the period character and/or hyphen character; * also allows for uppercase variations on property names for more idiomatic * shell use. * * <p> * For example, a call to {@code getProperty("foo.bar")} will attempt to find a * value for the original property or any 'equivalent' property, returning the * first found: * <ul> * <li>{@code foo.bar} - the original name</li> * <li>{@code foo_bar} - with underscores for periods (if any)</li> * <li>{@code FOO.BAR} - original, with upper case</li> * <li>{@code FOO_BAR} - with underscores and upper case</li> * </ul> * Any hyphen variant of the above would work as well, or even mix dot/hyphen * variants. * * <p> * The same applies for calls to {@link #containsProperty(String)}, which * returns {@code true} if any of the above properties are present, otherwise * {@code false}. * * <p> * This feature is particularly useful when specifying active or default * profiles as environment variables. The following is not allowable under Bash: * * <pre class="code"> * spring.profiles.active=p1 java -classpath ... MyApp * </pre> * * However, the following syntax is permitted and is also more conventional: * * <pre class="code"> * SPRING_PROFILES_ACTIVE=p1 java -classpath ... MyApp * </pre> * * <p> * Enable debug- or trace-level logging for this class (or package) for messages * explaining when these 'property name resolutions' occur. * * <p> * This property source is included by default in {@link StandardEnvironment} * and all its subclasses. * * @author Chris Beams * @author Juergen Hoeller * @since 3.1 * @see StandardEnvironment * @see AbstractEnvironment#getSystemEnvironment() * @see AbstractEnvironment#ACTIVE_PROFILES_PROPERTY_NAME */ public class SystemEnvironmentPropertySource extends MapPropertySource { /** * Create a new {@code SystemEnvironmentPropertySource} with the given name and * delegating to the given {@code MapPropertySource}. */ public SystemEnvironmentPropertySource(String name, Map<String, Object> source) { super(name, source); } /** * Return {@code true} if a property with the given name or any * underscore/uppercase variant thereof exists in this property source. */ @Override public boolean containsProperty(String name) { return (getProperty(name) != null); } /** * This implementation returns {@code true} if a property with the given name or * any underscore/uppercase variant thereof exists in this property source. */ @Override public Object getProperty(String name) { String actualName = resolvePropertyName(name); return super.getProperty(actualName); } /** * Check to see if this property source contains a property with the given name, * or any underscore / uppercase variation thereof. Return the resolved name if * one is found or otherwise the original name. Never returns {@code null}. */ protected final String resolvePropertyName(String name) { String resolvedName = checkPropertyName(name); if (resolvedName != null) { return resolvedName; } String uppercasedName = name.toUpperCase(); if (!name.equals(uppercasedName)) { resolvedName = checkPropertyName(uppercasedName); if (resolvedName != null) { return resolvedName; } } return name; } private String checkPropertyName(String name) { // Check name as-is if (containsKey(name)) { return name; } // Check name with just dots replaced String noDotName = name.replace('.', '_'); if (!name.equals(noDotName) && containsKey(noDotName)) { return noDotName; } // Check name with just hyphens replaced String noHyphenName = name.replace('-', '_'); if (!name.equals(noHyphenName) && containsKey(noHyphenName)) { return noHyphenName; } // Check name with dots and hyphens replaced String noDotNoHyphenName = noDotName.replace('-', '_'); if (!noDotName.equals(noDotNoHyphenName) && containsKey(noDotNoHyphenName)) { return noDotNoHyphenName; } // Give up return null; } private boolean containsKey(String name) { return (isSecurityManagerPresent() ? this.source.keySet().contains(name) : this.source.containsKey(name)); } protected boolean isSecurityManagerPresent() { return (System.getSecurityManager() != null); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/PropertyResolver.java
core/src/main/java/com/taobao/arthas/core/env/PropertyResolver.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; /** * Interface for resolving properties against any underlying source. * * @author Chris Beams * @author Juergen Hoeller * @since 3.1 * @see Environment * @see PropertySourcesPropertyResolver */ public interface PropertyResolver { /** * Return whether the given property key is available for resolution, i.e. if * the value for the given key is not {@code null}. */ boolean containsProperty(String key); /** * Return the property value associated with the given key, or {@code null} if * the key cannot be resolved. * * @param key the property name to resolve * @see #getProperty(String, String) * @see #getProperty(String, Class) * @see #getRequiredProperty(String) */ String getProperty(String key); /** * Return the property value associated with the given key, or * {@code defaultValue} if the key cannot be resolved. * * @param key the property name to resolve * @param defaultValue the default value to return if no value is found * @see #getRequiredProperty(String) * @see #getProperty(String, Class) */ String getProperty(String key, String defaultValue); /** * Return the property value associated with the given key, or {@code null} if * the key cannot be resolved. * * @param key the property name to resolve * @param targetType the expected type of the property value * @see #getRequiredProperty(String, Class) */ <T> T getProperty(String key, Class<T> targetType); /** * Return the property value associated with the given key, or * {@code defaultValue} if the key cannot be resolved. * * @param key the property name to resolve * @param targetType the expected type of the property value * @param defaultValue the default value to return if no value is found * @see #getRequiredProperty(String, Class) */ <T> T getProperty(String key, Class<T> targetType, T defaultValue); /** * Return the property value associated with the given key (never {@code null}). * * @throws IllegalStateException if the key cannot be resolved * @see #getRequiredProperty(String, Class) */ String getRequiredProperty(String key) throws IllegalStateException; /** * Return the property value associated with the given key, converted to the * given targetType (never {@code null}). * * @throws IllegalStateException if the given key cannot be resolved */ <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException; /** * Resolve ${...} placeholders in the given text, replacing them with * corresponding property values as resolved by {@link #getProperty}. * Unresolvable placeholders with no default value are ignored and passed * through unchanged. * * @param text the String to resolve * @return the resolved String (never {@code null}) * @throws IllegalArgumentException if given text is {@code null} * @see #resolveRequiredPlaceholders * @see org.springframework.util.SystemPropertyUtils#resolvePlaceholders(String) */ String resolvePlaceholders(String text); /** * Resolve ${...} placeholders in the given text, replacing them with * corresponding property values as resolved by {@link #getProperty}. * Unresolvable placeholders with no default value will cause an * IllegalArgumentException to be thrown. * * @return the resolved String (never {@code null}) * @throws IllegalArgumentException if given text is {@code null} or if any * placeholders are unresolvable * @see org.springframework.util.SystemPropertyUtils#resolvePlaceholders(String, * boolean) */ String resolveRequiredPlaceholders(String text) throws IllegalArgumentException; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/PropertySources.java
core/src/main/java/com/taobao/arthas/core/env/PropertySources.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; /** * Holder containing one or more {@link PropertySource} objects. * * @author Chris Beams * @author Juergen Hoeller * @since 3.1 * @see PropertySource */ public interface PropertySources extends Iterable<PropertySource<?>> { /** * Return whether a property source with the given name is contained. * * @param name the {@linkplain PropertySource#getName() name of the property * source} to find */ boolean contains(String name); /** * Return the property source with the given name, {@code null} if not found. * * @param name the {@linkplain PropertySource#getName() name of the property * source} to find */ PropertySource<?> get(String name); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/ConversionService.java
core/src/main/java/com/taobao/arthas/core/env/ConversionService.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; /** * A service interface for type conversion. This is the entry point into the * convert system. Call {@link #convert(Object, Class)} to perform a thread-safe * type conversion using this system. * * @author Keith Donald * @author Phillip Webb * @since 3.0 */ public interface ConversionService { /** * Return {@code true} if objects of {@code sourceType} can be converted to the * {@code targetType}. * <p> * If this method returns {@code true}, it means {@link #convert(Object, Class)} * is capable of converting an instance of {@code sourceType} to * {@code targetType}. * <p> * Special note on collections, arrays, and maps types: For conversion between * collection, array, and map types, this method will return {@code true} even * though a convert invocation may still generate a {@link ConversionException} * if the underlying elements are not convertible. Callers are expected to * handle this exceptional case when working with collections and maps. * * @param sourceType the source type to convert from (may be {@code null} if * source is {@code null}) * @param targetType the target type to convert to (required) * @return {@code true} if a conversion can be performed, {@code false} if not * @throws IllegalArgumentException if {@code targetType} is {@code null} */ boolean canConvert(Class<?> sourceType, Class<?> targetType); /** * Convert the given {@code source} to the specified {@code targetType}. * * @param source the source object to convert (may be {@code null}) * @param targetType the target type to convert to (required) * @return the converted object, an instance of targetType * @throws ConversionException if a conversion exception occurred * @throws IllegalArgumentException if targetType is {@code null} */ <T> T convert(Object source, Class<T> targetType); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/MapPropertySource.java
core/src/main/java/com/taobao/arthas/core/env/MapPropertySource.java
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.env; import java.util.Map; import org.apache.logging.log4j.util.PropertiesPropertySource; /** * {@link PropertySource} that reads keys and values from a {@code Map} object. * * @author Chris Beams * @author Juergen Hoeller * @since 3.1 * @see PropertiesPropertySource */ public class MapPropertySource extends EnumerablePropertySource<Map<String, Object>> { public MapPropertySource(String name, Map<String, Object> source) { super(name, source); } @Override public Object getProperty(String name) { return this.source.get(name); } @Override public boolean containsProperty(String name) { return this.source.containsKey(name); } @Override public String[] getPropertyNames() { return this.source.keySet().toArray(new String[0]); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/convert/StringToInetAddressConverter.java
core/src/main/java/com/taobao/arthas/core/env/convert/StringToInetAddressConverter.java
package com.taobao.arthas.core.env.convert; import java.net.InetAddress; import java.net.UnknownHostException; public class StringToInetAddressConverter implements Converter<String, InetAddress> { @Override public InetAddress convert(String source, Class<InetAddress> targetType) { try { return InetAddress.getByName(source); } catch (UnknownHostException e) { throw new IllegalArgumentException("Invalid InetAddress value '" + source + "'", e); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/convert/ConvertiblePair.java
core/src/main/java/com/taobao/arthas/core/env/convert/ConvertiblePair.java
package com.taobao.arthas.core.env.convert; /** * Holder for a source-to-target class pair. */ public final class ConvertiblePair { private final Class<?> sourceType; private final Class<?> targetType; /** * Create a new source-to-target pair. * * @param sourceType the source type * @param targetType the target type */ public ConvertiblePair(Class<?> sourceType, Class<?> targetType) { this.sourceType = sourceType; this.targetType = targetType; } public Class<?> getSourceType() { return this.sourceType; } public Class<?> getTargetType() { return this.targetType; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || obj.getClass() != ConvertiblePair.class) { return false; } ConvertiblePair other = (ConvertiblePair) obj; return this.sourceType.equals(other.sourceType) && this.targetType.equals(other.targetType); } @Override public int hashCode() { return this.sourceType.hashCode() * 31 + this.targetType.hashCode(); } @Override public String toString() { return this.sourceType.getName() + " -> " + this.targetType.getName(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/convert/StringToIntegerConverter.java
core/src/main/java/com/taobao/arthas/core/env/convert/StringToIntegerConverter.java
package com.taobao.arthas.core.env.convert; final class StringToIntegerConverter implements Converter<String, Integer> { @Override public Integer convert(String source, Class<Integer> targetType) { return Integer.parseInt(source); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/env/convert/StringToArrayConverter.java
core/src/main/java/com/taobao/arthas/core/env/convert/StringToArrayConverter.java
package com.taobao.arthas.core.env.convert; import java.lang.reflect.Array; import com.taobao.arthas.core.env.ConversionService; import com.taobao.arthas.core.util.StringUtils; final class StringToArrayConverter<T> implements Converter<String, T[]> { private ConversionService conversionService; public StringToArrayConverter(ConversionService conversionService) { this.conversionService = conversionService; } @Override public T[] convert(String source, Class<T[]> targetType) { String[] strings = StringUtils.tokenizeToStringArray(source, ","); @SuppressWarnings("unchecked") T[] values = (T[]) Array.newInstance(targetType.getComponentType(), strings.length); for (int i = 0; i < strings.length; ++i) { @SuppressWarnings("unchecked") T value = (T) conversionService.convert(strings[i], targetType.getComponentType()); values[i] = value; } return values; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false