1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package mobvista.dmp.datasource.bundle.service;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import com.alibaba.fastjson.JSONObject;
import com.google.common.util.concurrent.*;
import mobvista.dmp.common.Constants;
import mobvista.dmp.util.DateUtil;
import mobvista.dmp.util.MRUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import java.io.*;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;
/**
* @package: mobvista.dmp.datasource.bundle.service
* @author: wangjf
* @date: 2020-11-02
* @time: 11:22
* @email: jinfeng.wang@mobvista.com
*/
public class BundleMatchServer {
static Logger logger;
static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 20, 1000, TimeUnit.MILLISECONDS,
new LinkedBlockingDeque<>(20), new CustomizableThreadFactory("BundleMatchMain"), new ThreadPoolExecutor.CallerRunsPolicy());
private static String dt = DateUtil.format(new Date(), "yyyy-MM-dd");
public static void main(String[] args) throws JoranException, IOException {
String input = "";
String output = "";
if (args.length >= 2) {
input = args[0];
output = args[1];
}
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(output));
} catch (IOException e) {
logger.info("IOException -->> " + e.getMessage());
}
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
configurator.doConfigure(BundleMatchServer.class.getClassLoader().getResourceAsStream("logback-syslog.xml"));
logger = context.getLogger("BundleMatchMain");
long start = System.currentTimeMillis();
Set<String> pkgs = readFile(input);
logger.info("Correct PKS size -->> " + pkgs.size());
ListeningExecutorService listeningExecutor = MoreExecutors.listeningDecorator(poolExecutor);
MoreExecutors.addDelayedShutdownHook(listeningExecutor, 2, TimeUnit.SECONDS);
List<ListenableFuture<BundleClass>> futures = new CopyOnWriteArrayList<>();
List<BundleClass> resultList = new CopyOnWriteArrayList<>();
for (String pkg : pkgs) {
ListenableFuture listenableFuture = listeningExecutor.submit(() -> {
String packageName = request(pkg);
BundleClass bundleClass = new BundleClass();
bundleClass.setBundleId(pkg);
bundleClass.setPackageName(packageName);
return bundleClass;
});
Futures.addCallback(listenableFuture, new FutureCallback<BundleClass>() {
@Override
public void onSuccess(BundleClass bundleClass) {
if (StringUtils.isNotBlank(bundleClass.getPackageName())) {
logger.info("PKG -->> " + bundleClass.getBundleId() + ", ID -->> " + bundleClass.getPackageName());
resultList.add(bundleClass);
}
}
@Override
public void onFailure(Throwable t) {
// NO DO!
}
});
futures.add(listenableFuture);
}
for (ListenableFuture<BundleClass> future : futures) {
try {
BundleClass bundleClass = future.get();
if (StringUtils.isNotBlank(bundleClass.getPackageName())) {
assert out != null;
out.write(MRUtils.JOINER.join(bundleClass.getBundleId(), bundleClass.getPackageName()));
out.newLine();
}
} catch (InterruptedException | ExecutionException | IOException e) {
logger.info(e.getMessage());
}
}
assert out != null;
out.flush();
out.close();
long end = System.currentTimeMillis();
logger.info("Runtime -->> " + (end - start));
poolExecutor.shutdown();
if (poolExecutor.isShutdown()) {
System.exit(0);
}
}
public static Set<String> readFile(String filePath) {
Set<String> pkgSet = new HashSet<>();
try {
File file = new File(filePath);
if (file.isFile() && file.exists()) {
// 考虑到编码格式
InputStreamReader read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt;
while ((lineTxt = bufferedReader.readLine()) != null) {
if (Constants.adrPkgPtn.matcher(lineTxt).matches()) {
pkgSet.add(lineTxt);
}
}
bufferedReader.close();
read.close();
} else {
logger.info("NOT FOUND !");
}
} catch (Exception e) {
logger.info("Read File Error !Exception -->> " + e.getMessage());
}
return pkgSet;
}
public static String request(String packageName) {
CloseableHttpClient client = HttpClients.createDefault();
List<BasicNameValuePair> formparams = new ArrayList<>();
final String serverUrl = "http://itunes.apple.com/lookup";
URIBuilder uri = new URIBuilder();
try {
uri = new URIBuilder(serverUrl).addParameter("bundleId", packageName);
} catch (URISyntaxException e) {
e.printStackTrace();
}
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10000).setConnectionRequestTimeout(10000)
.setSocketTimeout(10000).build();
HttpGet httpGet = new HttpGet();
String trackId = "";
CloseableHttpResponse response;
try {
httpGet = new HttpGet(uri.build());
httpGet.setConfig(requestConfig);
response = client.execute(httpGet);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
JSONObject jsonObject = Constants.String2JSONObject(result.toString());
if (jsonObject.containsKey("resultCount") && jsonObject.containsKey("results") && jsonObject.getInteger("resultCount") > 0 && jsonObject.getJSONArray("results") != null && jsonObject.getJSONArray("results").size() > 0) {
JSONObject json = jsonObject.getJSONArray("results").getJSONObject(0);
if (json.containsKey("trackId")) {
trackId = json.getString("trackId");
}
}
} catch (URISyntaxException | IOException e) {
// logger.info("URISyntaxException | IOException -->> " + e.getMessage());
} finally {
httpGet.abort();
}
return trackId;
}
}