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

alibaba / java-dns-cache-manipulator / 1258

pending completion
1258

Pull #177

Appveyor

web-flow
Merge 977c5b885 into 0aea6a819
Pull Request #177: chore(deps): bump org.apache.commons:commons-lang3 from 3.12.0 to 3.13.0

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