Child: [9bda86] (diff)

Download this file

PackageUniverseBuilder.java    247 lines (206 with data), 10.0 kB

  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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/**
* Copyright (c) 2013/2014 Verein zur Foerderung der IT-Sicherheit in Oesterreich (SBA).
* The work has been developed in the TIMBUS Project and the above-mentioned are Members of the TIMBUS Consortium.
* TIMBUS is supported by the European Union under the 7th Framework Programme for research and technological
* development and demonstration activities (FP7/2007-2013) under grant agreement no. 269940.
*
* 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, including without
* limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTIBITLY, or FITNESS FOR A PARTICULAR
* PURPOSE. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law or agreed to in writing, shall any Contributor be liable for damages, including
* any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this
* License or out of the use or inability to use the Work.
* See the License for the specific language governing permissions and limitation under the License.
*/
package net.timbusproject.dpes.alternative.kb;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.io.IOUtils;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
* @author Rudolf Mayer
*/
public class PackageUniverseBuilder {
public static final String aptitudeSearchCommand = "aptitude search -F %p \".*\"";
private static final XStream xStream = new XStream(new DomDriver());
static final Logger logUniverse = Logger.getLogger("PackaUniverseBuilder");
public static void main(String[] args) throws IOException {
long startTime = System.currentTimeMillis();
// search all packages
ArrayList<String> allPackageNames = VirtualPackageAlternativeIdentifier.searchPackages(aptitudeSearchCommand);
SortedMap<String, Package> allPackages = new TreeMap<String, Package>();
System.out.println("Found " + allPackageNames.size() + " packages.\n");
Options options = new Options();
Option optLoadProviders = new Option("f", "file", true, "Load package information from an XML serialised file");
options.addOption(optLoadProviders);
CommandLineParser parser = new BasicParser();
try {
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("file")) { // load the package information from the file
String providersFileName = cmd.getOptionValue("file");
logUniverse.info("Trying to load package information from XML " + providersFileName);
allPackages = (SortedMap<String, Package>) xStream.fromXML(new File(providersFileName));
logUniverse.info("\tDone!");
}
} catch (ParseException e) {
System.err.println("CLI parsing failed. Reason: " + e.getMessage());
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("ant", options);
return;
}
if (allPackages == null) {
allPackages = new TreeMap<String, Package>();
// allPackages = new HashMap<String, Package>(allPackageNames.size());
}
// query the package information, in parallel manner
int nrOfProcessors = Runtime.getRuntime().availableProcessors();
ExecutorService eservice = Executors.newFixedThreadPool(nrOfProcessors);
logUniverse.info("*** Working with " + nrOfProcessors + " parallel processes");
List<Future<Package>> futuresList = new ArrayList<Future<Package>>();
int maxTestCount = 50;
int index = 0;
for (String packageName : allPackageNames) {
index++;
// check if we need to query this package
if (allPackages.containsKey(packageName)) {
logUniverse.info("Not querying already loaded package " + packageName);
} else {
futuresList.add(eservice.submit(new PackgeDetailsTask(packageName)));
}
// if (index == maxTestCount) {
// break;
// }
}
eservice.shutdown();
try {
eservice.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
System.out.println(e);
}
for (Future<Package> future : futuresList) {
Package pkg;
try {
pkg = future.get();
allPackages.put(pkg.getName(), pkg);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
// save packages in XML
final String fileName = "packages-" + OSIdentifier.getEscapedOSString() + ".xml";
try {
logUniverse.info("Wrote packages to "
+ VirtualPackageAlternativeIdentifier.writeAsXML(allPackages, fileName).getAbsolutePath());
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
long endReadingPackagesTime = System.currentTimeMillis();
// process all packages
for (Package pkg : allPackages.values()) {
// process the lines
for (String str : pkg.getPackageInformation()) {
str = str.trim();
String[] parts = str.split(":");
String key = parts[0].trim();
if (parts.length == 1) {
continue;
}
String value = str.substring(parts[0].length() + 1).trim();
if (key.equals("Package")) {
pkg.setName(parts[1]);
} else if (key.equals("Depends")) {
pkg.setDependsString(parts[1]);
} else if (key.equals("Conflicts")) {
pkg.setConflictsString(parts[1]);
} else if (key.equals("Recommends")) {
pkg.setRecommendsString(parts[1]);
} else if (key.equals("Version")) {
pkg.setVersionString(parts[1]);
}
}
if (allPackages.size() == 10) {
break;
}
}
// do post-processing ==> after all packages are read, we can resolve the links
for (Package pkg : allPackages.values()) {
pkg.resolveLinks(allPackages);
}
long totalEndTime = System.currentTimeMillis();
logUniverse.info("");
}
public static String inputStreamToString(Process process) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(process.getInputStream(), writer);
return writer.toString();
}
}
class PackgeDetailsTask implements Callable<Package> {
static final Logger logPackageDetails = Logger.getLogger("PackaDetailsQuery");
private final String packageName;
public PackgeDetailsTask(String packageName) {
this.packageName = packageName;
}
@Override
public Package call() {
Package pkg = new Package();
pkg.setName(packageName);
String aptShowCommand = "aptitude show " + packageName;
aptShowCommand = "apt-cache show " + packageName;
ProcessBuilder processBuilder = new ProcessBuilder(new String[] { "/bin/sh", "-c", aptShowCommand });
logPackageDetails.info("Querying " + packageName);
try {
Process process = processBuilder.start();
// read package details into a data structure
List<String> intialPackageLines;
intialPackageLines = IOUtils.readLines(process.getInputStream());
// process elements that span multi-lines
ArrayList<String> processedPackageLines = new ArrayList<String>();
for (String string : intialPackageLines) {
if (string.startsWith(" ")) {
int index = processedPackageLines.size() - 1;
String line = processedPackageLines.get(index) + System.getProperty("line.separator") + string;
processedPackageLines.remove(index);
processedPackageLines.add(line);
} else {
processedPackageLines.add(string);
}
}
pkg.setPackageInformation(processedPackageLines);
logPackageDetails.info("\tfinished " + packageName);
return pkg;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}