]> git.argeo.org Git - gpl/argeo-slc.git/blob - core/YumListParser.java
Prepare next development cycle
[gpl/argeo-slc.git] / core / YumListParser.java
1 package org.argeo.slc.rpmfactory.core;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.util.Set;
6 import java.util.StringTokenizer;
7 import java.util.TreeSet;
8
9 import org.apache.commons.io.IOUtils;
10 import org.apache.commons.io.LineIterator;
11 import org.apache.commons.logging.Log;
12 import org.apache.commons.logging.LogFactory;
13 import org.argeo.slc.SlcException;
14 import org.springframework.core.io.Resource;
15
16 /**
17 * Reads the output of a 'yum list all' command and interpret the list of
18 * packages.
19 */
20 public class YumListParser implements RpmPackageSet {
21 private final static Log log = LogFactory.getLog(YumListParser.class);
22
23 private Set<String> installed = new TreeSet<String>();
24 /** Not installed but available */
25 private Set<String> installable = new TreeSet<String>();
26
27 private Resource yumListOutput;
28
29 public void init() {
30 try {
31 if (yumListOutput != null) {
32 load(yumListOutput.getInputStream());
33 if (log.isDebugEnabled())
34 log.debug(installed.size() + " installed, "
35 + installable.size() + " installable, from "
36 + yumListOutput);
37 }
38 } catch (IOException e) {
39 throw new SlcException("Cannot initialize yum list parser", e);
40 }
41 }
42
43 public Boolean contains(String packageName) {
44 if (installed.contains(packageName))
45 return true;
46 else
47 return installable.contains(packageName);
48 }
49
50 protected void load(InputStream in) {
51 try {
52 Boolean readingInstalled = false;
53 Boolean readingAvailable = false;
54 LineIterator it = IOUtils.lineIterator(in, "UTF-8");
55 while (it.hasNext()) {
56 String line = it.nextLine();
57 if (line.trim().equals("Installed Packages")) {
58 readingInstalled = true;
59 } else if (line.trim().equals("Available Packages")) {
60 readingAvailable = true;
61 readingInstalled = false;
62 } else if (readingAvailable) {
63 if (Character.isLetterOrDigit(line.charAt(0))) {
64 installable.add(extractRpmName(line));
65 }
66 } else if (readingInstalled) {
67 if (Character.isLetterOrDigit(line.charAt(0))) {
68 installed.add(extractRpmName(line));
69 }
70 }
71 }
72 } catch (IOException e) {
73 throw new SlcException("Cannot load yum list output", e);
74 } finally {
75 IOUtils.closeQuietly(in);
76 }
77 }
78
79 protected String extractRpmName(String line) {
80 StringTokenizer st = new StringTokenizer(line, " \t");
81 String packageName = st.nextToken();
82 return packageName.split("\\.")[0];
83 }
84
85 public Set<String> getInstalled() {
86 return installed;
87 }
88
89 public Set<String> getInstallable() {
90 return installable;
91 }
92
93 public void setYumListOutput(Resource yumListOutput) {
94 this.yumListOutput = yumListOutput;
95 }
96
97 }