1 package org.cyclopsgroup.jmxterm;
2
3 import org.apache.commons.beanutils.ConvertUtils;
4 import org.apache.commons.io.output.NullOutputStream;
5 import org.apache.commons.lang3.ClassUtils;
6 import org.apache.commons.lang3.StringUtils;
7 import org.apache.commons.lang3.math.NumberUtils;
8 import org.cyclopsgroup.jmxterm.utils.ValueFormat;
9
10 import javax.management.remote.JMXServiceURL;
11 import java.io.IOException;
12 import java.io.PrintStream;
13 import java.util.regex.Pattern;
14
15
16
17
18
19
20 public final class SyntaxUtils {
21
22
23
24 public static final String NULL = ValueFormat.NULL;
25
26
27
28
29 public static final PrintStream NULL_PRINT_STREAM = new PrintStream(new NullOutputStream(), true);
30
31 private static final Pattern PATTERN_HOST_PORT = Pattern.compile("^(\\w|\\.|\\-)+\\:\\d+$");
32
33
34
35
36
37
38
39 public static JMXServiceURL getUrl(String url, JavaProcessManager jpm) throws IOException {
40 if (StringUtils.isEmpty(url)) {
41 throw new IllegalArgumentException("Empty URL is not allowed");
42 } else if (NumberUtils.isDigits(url) && jpm != null) {
43 Integer pid = Integer.parseInt(url);
44 JavaProcess p;
45
46 p = jpm.get(pid);
47 if (p == null) {
48 throw new NullPointerException("No such PID " + pid);
49 }
50 if (!p.isManageable()) {
51 p.startManagementAgent();
52 if (!p.isManageable()) {
53 throw new IllegalStateException("Managed agent for PID " + pid + " couldn't start. PID "
54 + pid + " is not manageable");
55 }
56 }
57 return new JMXServiceURL(p.toUrl());
58
59 } else if (PATTERN_HOST_PORT.matcher(url).find()) {
60 return new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + url + "/jmxrmi");
61 } else {
62 return new JMXServiceURL(url);
63 }
64 }
65
66
67
68
69
70
71
72 public static boolean isNull(String s) {
73 return StringUtils.equalsIgnoreCase(NULL, s) || StringUtils.equals("*", s);
74 }
75
76
77
78
79
80
81
82
83 public static Object parse(String expression, String type) {
84 if (expression == null || StringUtils.equalsIgnoreCase(NULL, expression)) {
85 return null;
86 }
87 Class<?> c;
88 try {
89 c = ClassUtils.getClass(type);
90 } catch (ClassNotFoundException e) {
91 throw new IllegalArgumentException("Type " + type + " isn't valid", e);
92 }
93 if (c == String.class) {
94 return expression;
95 }
96 if (StringUtils.isEmpty(expression)) {
97 return null;
98 }
99 return ConvertUtils.convert(expression, c);
100 }
101
102 private SyntaxUtils() {}
103 }