• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

alibaba / java-dns-cache-manipulator / 1267

pending completion
1267

push

Appveyor

oldratlee
chore(ci): upgrade CI JDK ๐Ÿค–

527 of 645 relevant lines covered (81.71%)

0.82 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

65.82
/tool/src/main/java/com/alibaba/dcm/tool/DcmTool.java
1
package com.alibaba.dcm.tool;
2

3
import com.alibaba.dcm.agent.DcmAgent;
4
import com.sun.tools.attach.*;
5
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
6
import org.apache.commons.cli.*;
7

8
import javax.annotation.Nonnull;
9
import java.io.IOException;
10
import java.lang.management.ManagementFactory;
11
import java.nio.file.Files;
12
import java.nio.file.Paths;
13
import java.util.List;
14
import java.util.Scanner;
15

16
import static java.lang.System.exit;
17
import static java.nio.charset.StandardCharsets.UTF_8;
18

19
/**
20
 * DCM Tool.
21
 *
22
 * @author Jerry Lee (oldratlee at gmail dot com)
23
 * @since 1.4.0
24
 */
25
public class DcmTool {
ร—
26
    static final String DCM_TOOLS_TMP_FILE_KEY = "DCM_TOOLS_TMP_FILE";
27
    static final String DCM_TOOLS_AGENT_JAR_KEY = "DCM_TOOLS_AGENT_JAR";
28

29
    private static final String DCM_AGENT_SUCCESS_MARK_LINE = "!!DCM SUCCESS!!";
30

31
    private static final List<String> actionList = DcmAgent.getActionList();
1โœ”
32

33
    /**
34
     * entry main method.
35
     */
36
    @SuppressFBWarnings("THROWS_METHOD_THROWS_CLAUSE_BASIC_EXCEPTION")
37
    public static void main(@Nonnull String[] args) throws Exception {
38
        final CommandLine cmd = parseCommandLine(args);
1โœ”
39

40
        final String[] arguments = cmd.getArgs();
1โœ”
41
        if (arguments.length < 1) {
1โœ”
42
            System.out.println("No Action! Available action: " + actionList);
ร—
43
            exit(2);
ร—
44
        }
45

46
        final String action = arguments[0].trim();
1โœ”
47
        if (!actionList.contains(action)) {
1โœ”
48
            throw new IllegalStateException("Unknown action " + action + ". Available action: " + actionList);
ร—
49
        }
50

51
        final String pid;
52
        if (cmd.hasOption('p')) {
1โœ”
53
            pid = cmd.getOptionValue('p');
1โœ”
54
        } else {
55
            pid = selectProcess();
ร—
56
        }
57

58
        doDcmActionViaAgent(action, arguments, pid);
1โœ”
59
    }
1โœ”
60

61
    @Nonnull
62
    private static CommandLine parseCommandLine(@Nonnull String[] args) throws ParseException {
63
        final Options options = new Options();
1โœ”
64
        options.addOption("p", "pid", true, "java process id to attach");
1โœ”
65
        options.addOption("h", "help", false, "show help");
1โœ”
66

67
        CommandLineParser parser = new DefaultParser();
1โœ”
68
        CommandLine cmd = parser.parse(options, args);
1โœ”
69

70
        if (cmd.hasOption('h')) {
1โœ”
71
            HelpFormatter hf = new HelpFormatter();
ร—
72
            hf.printHelp("Options", options);
ร—
73
            exit(0);
ร—
74
        }
75

76
        return cmd;
1โœ”
77
    }
78

79
    private static void doDcmActionViaAgent(@Nonnull String action, @Nonnull String[] arguments, @Nonnull String pid)
80
            throws AttachNotSupportedException, IOException, AgentLoadException, AgentInitializationException {
81
        final String tmpFile = getConfig(DCM_TOOLS_TMP_FILE_KEY);
1โœ”
82
        final String agentJar = getConfig(DCM_TOOLS_AGENT_JAR_KEY);
1โœ”
83

84
        final StringBuilder agentArgument = new StringBuilder();
1โœ”
85
        agentArgument.append(action);
1โœ”
86
        for (int i = 1; i < arguments.length; i++) {
1โœ”
87
            String s = arguments[i];
1โœ”
88
            agentArgument.append(' ').append(s);
1โœ”
89
        }
90
        agentArgument.append(" file ").append(tmpFile);
1โœ”
91

92
        VirtualMachine vm = null; // target java process pid
1โœ”
93
        boolean actionSuccess;
94
        try {
95
            vm = VirtualMachine.attach(pid);
1โœ”
96
            vm.loadAgent(agentJar, agentArgument.toString()); // loadAgent method will wait to agentmain finished.
1โœ”
97

98
            actionSuccess = printDcmResult(tmpFile);
1โœ”
99
        } finally {
100
            if (null != vm) {
1โœ”
101
                vm.detach();
1โœ”
102
            }
103
        }
104

105
        if (!actionSuccess) {
1โœ”
106
            exit(1);
ร—
107
        }
108
    }
1โœ”
109

110
    private static boolean printDcmResult(@Nonnull String tmpFile) throws IOException {
111
        boolean actionSuccess = false;
1โœ”
112

113
        final List<String> lines = Files.readAllLines(Paths.get(tmpFile), UTF_8);
1โœ”
114

115
        final int lastIdx = lines.size() - 1;
1โœ”
116
        final String lastLine = lines.get(lastIdx);
1โœ”
117
        if (DCM_AGENT_SUCCESS_MARK_LINE.equals(lastLine)) {
1โœ”
118
            lines.remove(lastIdx);
1โœ”
119
            actionSuccess = true;
1โœ”
120
        }
121

122
        for (String line : lines) {
1โœ”
123
            System.out.println(line);
1โœ”
124
        }
1โœ”
125

126
        return actionSuccess;
1โœ”
127
    }
128

129
    ///////////////////////////////////////////////
130
    // util methods
131
    ///////////////////////////////////////////////
132

133
    @Nonnull
134
    private static String getConfig(@Nonnull String name) {
135
        String var = System.getenv(name);
1โœ”
136
        if (var == null || var.trim().length() == 0) {
1โœ”
137
            var = System.getProperty(name);
1โœ”
138
        }
139
        if (var == null || var.trim().length() == 0) {
1โœ”
140
            throw new IllegalStateException("fail to var " + name + ", is absent or blank string!");
ร—
141
        }
142

143
        return var;
1โœ”
144
    }
145

146
    @Nonnull
147
    @SuppressFBWarnings("DM_DEFAULT_ENCODING")
148
    private static String selectProcess() {
149
        System.out.println("Which java process to attache:");
ร—
150
        final List<VirtualMachineDescriptor> list = VirtualMachine.list();
ร—
151

152
        // remove current process
153
        list.removeIf(vm -> vm.id().equals(pid()));
ร—
154

155
        for (int i = 0; i < list.size(); i++) {
ร—
156
            final VirtualMachineDescriptor vm = list.get(i);
ร—
157
            System.out.printf("%d) %-5s %s%n", i + 1, vm.id(), vm.displayName());
ร—
158
        }
159

160
        Scanner in = new Scanner(System.in);
ร—
161
        while (true) {
162
            System.out.print("?# ");
ร—
163
            final String select = in.nextLine();
ร—
164
            try {
165
                final int idx = Integer.parseInt(select);
ร—
166
                if (idx > 0 && idx <= list.size()) {
ร—
167
                    return list.get(idx - 1).id();
ร—
168
                }
169
                System.out.println("Invalid selection!");
ร—
170
            } catch (NumberFormatException e) {
ร—
171
                System.out.println("Invalid input, not number!");
ร—
172
            }
ร—
173
        }
ร—
174
    }
175

176
    @Nonnull
177
    static String pid() {
178
        final String name = ManagementFactory.getRuntimeMXBean().getName();
1โœ”
179
        final int idx = name.indexOf("@");
1โœ”
180
        return name.substring(0, idx);
1โœ”
181
    }
182
}
STATUS ยท Troubleshooting ยท Open an Issue ยท Sales ยท Support ยท CAREERS ยท ENTERPRISE ยท START FREE ยท SCHEDULE DEMO
ANNOUNCEMENTS ยท TWITTER ยท TOS & SLA ยท Supported CI Services ยท What's a CI service? ยท Automated Testing

ยฉ 2025 Coveralls, Inc