Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (107)
games submitted by our members
Games in WIP (534)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  How would you improve this api?  (Read 917 times)
0 Members and 1 Guest are viewing this topic.
Offline i30817

Junior Member





« Posted 2009-08-01 23:58:53 »

I did a abstraction over both zip and rar to find and extract files. It works ok, but my api is not as elegant as i wanted. I tended to use abstract classes instead of interfaces in the implementation.

The improvements on the api would be mostly on the Selector class 2 posts bellow. Notice that i use a interface on some ordering / selection functions that returns a comparator given an Extractor (the abstract class that extracts characteristics or files from compressed file). I thought about using comparator simply, but i needed access to the extraction functions (that are on the Extractor implementation). The api is "strange" because it receives objects that only each comparator knows about, dunno about that.

I actually found a really niffy way to use a enum as a way to aggregate commonly used implementations with this, so extracting / ordering is sweet and easy ( orderByAscending for ex), and i wonder if fresh eyes would see a way to apply/aggregate that pattern to the other functions (there is one there that uses another enum Inequality).

Notice that i tried to implement a self-reflective api (like lists and the sublist method) by implementing the methods inverseSelector() and subSelector() that allow me to do fairly simple set operations like only select from this subset, or only select from other files, etc. I'd also like to know if i missed something obvious here.

First a sample usage:
Offline i30817

Junior Member





« Reply #1 - Posted 2009-08-01 23:59:18 »


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  
        Selector archive = null;
        try {
            //may have to download...
           archive = Extractor.from(origin);
            //can't read, ignore
           if (archive == null) {
                throw new IOException("Can't read " + origin.toString() + " as compressed File");
            }
            //find supported formats inside the file
           StringBuilder regex = new StringBuilder();
            Iterator<String> it = BookLoader.setOfSupportedExtensions().iterator();

            if (it.hasNext()) {
                regex.append("(?:.*\\.").append(it.next()).append("$)");
            }

            while (it.hasNext()) {
                regex.append("|(?:.*\\.").append(it.next()).append("$)");
            }

            archive.selectByRegex(regex.toString(), Pattern.CASE_INSENSITIVE);
            FileView fv = archive.getSelectedMax(Content.FileSize);
            if (fv == null) {
                throw new IOException("No parseable file in compressed file");
            }
            BookLoader loader = BookLoader.forName(fv.getFileName());
            return loader.create(fv.getInputStream(), reparse);
        } finally {
            IoUtils.close(archive);
        }


Then the Selector implementation:
Offline i30817

Junior Member





« Reply #2 - Posted 2009-08-02 00:01:24 »

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  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
282  
283  
284  
285  
286  
287  
288  
289  
290  
291  
292  
293  
294  
295  
296  
297  
298  
299  
300  
301  
302  
303  
304  
305  
306  
307  
@SuppressWarnings(value = "unchecked")
public final class Selector implements Closeable, Iterable<FileView> {

    private List headers;
    private Extractor extractor;
    private Set workSet;

    public Selector(Extractor extractor) {
        this(extractor, extractor.getFileHeaders());
    }

    private Selector(Extractor extractor, List headers) {
        this.headers = headers;
        this.extractor = extractor;
        this.workSet = new LinkedHashSet(headers.size() * 2);
    }

    public boolean isEmpty() {
        return headers.isEmpty();
    }

    public int selectedSize() {
        return workSet.size();
    }

    public int size() {
        return headers.size();
    }

    public void clear() {
        workSet.clear();
    }

    public void close() throws IOException {
        if (extractor == null) {
            return;
        }
        extractor.close();
        headers = null;
        workSet = null;
        extractor = null;
    }

    public Selector subSelector() {
        if (workSet.size() == headers.size()) {
            workSet.clear();
            return this;
        } else if (workSet.size() == 0) {
            return new Selector(extractor, Collections.EMPTY_LIST);
        }
        return new Selector(extractor, new ArrayList(workSet));
    }
    public Selector inverseSelector() {
        if (workSet.size() == 0) {
            return this;
        } else if (workSet.size() == headers.size()) {
            return new Selector(extractor, Collections.EMPTY_LIST);
        }
        //removing in arraylists is painfull
       LinkedList arr = new LinkedList(headers);
        arr.removeAll(workSet);
        return new Selector(extractor, arr);
    }
    public Selector selectAll() {
        for (Object h : headers) {
            workSet.add(h);
        }
        return this;
    }
    public Selector selectByCRC32(long crc32) {
        for (Object h : headers) {
            Long crc = extractor.getCRC32(h);
            if (crc != null && (crc & 0X00000000ffffffffL) == (crc32 & 0X00000000ffffffffL)) {
                workSet.add(h);
            }
        }
        return this;
    }
    public Selector selectByCompressedFileSize(Inequality i, long size) {
        if (i == null) {
            return this;
        }
        for (Object h : headers) {
            Long fs = extractor.getCompressedFileSize(h);
            if (i.TEST(fs, size)) {
                workSet.add(h);
            }
        }
        return this;
    }
    public Selector selectByFileSize(Inequality i, long size) {
        if (i == null) {
            return this;
        }
        for (Object h : headers) {
            Long fs = extractor.getFileSize(h);
            if (i.TEST(fs, size)) {
                workSet.add(h);
            }
        }
        return this;
    }
    public Selector selectByModificationDate(Inequality i, DateFormat format, String datePattern) {
        if (i == null || format == null || datePattern == null) {
            return this;
        }
        try {
            Date givenDate = format.parse(datePattern);
            for (Object h : headers) {
                Date archiveDate = extractor.getModificationDate(h);
                if (archiveDate == null) {
                    continue;
                }
                Date comparableDate = format.parse(format.format(archiveDate));
                if (i.TEST(comparableDate, givenDate)) {
                    workSet.add(h);
                }
            }
        } catch (ParseException ex) {
            throw new IllegalArgumentException("Formatter can't parse given datePattern", ex);
        }
        return this;
    }
    public Selector selectByModificationDate(Inequality i, Date date) {
        if (i == null || date == null) {
            return this;
        }

        for (Object h : headers) {
            Date archiveDate = extractor.getModificationDate(h);
            if (archiveDate == null) {
                continue;
            }
            if (i.TEST(archiveDate, date)) {
                workSet.add(h);
            }
        }
        return this;
    }
    public Selector selectByName(String name, boolean caseSensitive) {
        if (name == null) {
            return this;
            //Archived name is never null...
       }
        if (caseSensitive) {
            for (Object h : headers) {
                if (extractor.getFileName(h).equals(name)) {
                    workSet.add(h);
                }
            }
        } else {
            for (Object h : headers) {
                if (extractor.getFileName(h).toLowerCase(Locale.ENGLISH).equals(name.toLowerCase(Locale.ENGLISH))) {
                    workSet.add(h);
                }
            }
        }
        return this;
    }
    public Selector selectByName(Inequality i, String s) {
        if (i == null || s == null) {
            return this;
            //name is never null...
       }
        Comparator<String> natural = Strings.getNaturalComparator();
        for (Object h : headers) {
            if (i.TEST(extractor.getFileName(h), s, natural)) {
                workSet.add(h);
            }
        }
        return this;
    }
    public Selector selectByRegex(String regex) {
        if (regex == null) {
            return this;
            //name never null
       }
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher("");
        for (Object h : headers) {
            m.reset(extractor.getFileName(h));
            if (m.matches()) {
                workSet.add(h);
            }
        }
        return this;
    }
    public Selector selectByRegex(String regex, int flags) {
        if (regex == null) {
            return this;
            //name never null
       }
        Pattern p = Pattern.compile(regex, flags);
        Matcher m = p.matcher("");
        for (Object h : headers) {
            m.reset(extractor.getFileName(h));
            if (m.matches()) {
                workSet.add(h);
            }
        }
        return this;
    }
    public Selector selectBySuffix(String suffix, boolean caseSensitive) {
        if (suffix == null) {
            return this;
        }
        //Archived name is never null...
       if (caseSensitive) {
            for (Object h : headers) {
                if (extractor.getFilePath(h).endsWith(suffix)) {
                    workSet.add(h);
                }
            }
        } else {
            for (Object h : headers) {
                if (extractor.getFilePath(h).toLowerCase(Locale.ENGLISH).endsWith(suffix.toLowerCase(Locale.ENGLISH))) {
                    workSet.add(h);
                }
            }
        }
        return this;
    }
    public Selector orderByAscending(FileComparator c) {
        Object[] a = workSet.toArray();
        Arrays.sort(a, c.getComparator(extractor));
        workSet = new LinkedHashSet(a.length * 2);
        for (int i = 0; i < a.length; i++) {
            workSet.add(a[i]);
        }
        return this;
    }
    public FileView getSelected() {
        Iterator it = workSet.iterator();
        if (it.hasNext()) {
            return new FileView(it.next(), extractor);
        } else {
            return null;
        }
    }
    public FileView getSelectedMax(FileComparator c) {
        try {
            Object header = Collections.max(workSet, c.getComparator(extractor));
            return new FileView(header, extractor);
        } catch (NoSuchElementException ex) {
            return null;
        }
    }
    public FileView getSelectedMin(FileComparator c) {
        try {
            Object header = Collections.min(workSet, c.getComparator(extractor));
            return new FileView(header, extractor);
        } catch (NoSuchElementException ex) {
            return null;
        }
    }
    public Selector orderByDescending(FileComparator c) {
        Object[] a = workSet.toArray();
        Arrays.sort(a, Collections.reverseOrder(c.getComparator(extractor)));
        workSet = new LinkedHashSet(a.length * 2);
        for (int i = 0; i < a.length; i++) {
            workSet.add(a[i]);
        }
        return this;
    }
    public ContentsIterator iterator() {
        return new ContentsIterator(workSet.iterator(), workSet.size(), extractor);
    }

    public ContentsIterator iterator(int numberToExtract) {
        int toExtract = Math.max(0, Math.min(numberToExtract, workSet.size()));
        return new ContentsIterator(workSet.iterator(), toExtract, extractor);
    }

    public static final class ContentsIterator implements Iterator<FileView>, Iterable<FileView> {

        private Iterator headerCopy;
        private Extractor extractor;
        private int size, index;

        private ContentsIterator(Iterator headerCopy, int size, Extractor extractor) {
            this.headerCopy = headerCopy;
            this.size = size;
            this.extractor = extractor;
        }

        public Iterator<FileView> iterator() {
            return this;
        }

        public boolean hasNext() {
            return index < size;
        }

        public FileView next() {
            if (hasNext()) {
                index++;
                return new FileView(headerCopy.next(), extractor);
            } else {
                throw new NoSuchElementException();
            }
        }

        public void remove() {
            headerCopy.remove();
        }
    }
}
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline i30817

Junior Member





« Reply #3 - Posted 2009-08-02 00:08:50 »

Another, more hairy use of the api (to extract images based on file name (cover))
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  
        try {
            archive = Extractor.from(file);
            if(archive == null)
                return null;

            regex = "(?:.*\\.jpg$)|(?:.*\\.png$)|(?:.*\\.gif$)|(?:.*\\.bmp$)";

            archive.selectByRegex(regex, Pattern.CASE_INSENSITIVE);
            if (archive.selectedSize() == 0) {
                return null;
            }
            //only png, gif etc
           archive = archive.subSelector();
            regex = "(?:.*rear.*)|(?:.*back.*)";
            archive.selectByRegex(regex, Pattern.CASE_INSENSITIVE);
            //not a back cover
           archive = archive.inverseSelector();
            if (archive.isEmpty()) {
                return null;
            } else {
                //ordered by least false positives.
               regex = "(?:.*fcover.*)|(?:.*front.*)|(?:.*cover.*)|(?:^fc\\..*)";
                archive.selectByRegex(regex, Pattern.CASE_INSENSITIVE);
                imageFileView = archive.getSelected();
            }

            if (imageFileView == null) {
                archive.selectAll();
                archive.orderByDescending(Content.NameSize);
                //introduce some fuzziness for this particular search
               //(remove missing or additional "_" or " " or "'")
               Pattern p = Pattern.compile("(?:_| |')");
                String archiveFileName = p.matcher(file.getName().toLowerCase()).replaceAll("");
                for (FileView fv : archive) {
                    String fileName = fv.getFileName();
                    //remove the extension (for .zip and .rar for now so 4)
                   fileName = fileName.substring(0, fileName.length() - 4);
                    //disregard strings too likely to occur in the archive name
                   if (likelySubString(fileName)) {
                        break;
                    } else if (archiveFileName.contains(p.matcher(fileName.toLowerCase()).replaceAll(""))) {
                        imageFileView = fv;
                        break;
                    }
                }
            }
            if (imageFileView != null) {
                imageInput = imageFileView.getInputStream();
                BufferedImage image = ImageIO.read(imageInput);
                if (image != null && imageTooSmall(image)) {
                    image.getGraphics().dispose();
                    return null;
                }
                return image;
            }
        } finally {
            IoUtils.close(imageInput, archive);
        }
Offline i30817

Junior Member





« Reply #4 - Posted 2009-08-06 16:21:28 »

No suggestions eh?
 Undecided

 Lips Sealed

 Cry

 persecutioncomplex
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

pw (35 views)
2014-07-24 01:59:36

Riven (33 views)
2014-07-23 21:16:32

Riven (21 views)
2014-07-23 21:07:15

Riven (24 views)
2014-07-23 20:56:16

ctomni231 (55 views)
2014-07-18 06:55:21

Zero Volt (47 views)
2014-07-17 23:47:54

danieldean (38 views)
2014-07-17 23:41:23

MustardPeter (43 views)
2014-07-16 23:30:00

Cero (59 views)
2014-07-16 00:42:17

Riven (56 views)
2014-07-14 18:02:53
HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54

HotSpot Options
by Roquen
2014-05-06 15:03:10

Escape Analysis
by Roquen
2014-04-29 22:16:43

Experimental Toys
by Roquen
2014-04-28 13:24:22
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!