1/*
2 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24package sun.hotspot.tools.ctw;
25
26import java.io.IOException;
27import java.io.InputStream;
28import java.nio.file.Files;
29import java.nio.file.Path;
30import java.util.jar.JarEntry;
31import java.util.jar.JarFile;
32import java.util.stream.Stream;
33
34/**
35 * Handler for jar-files containing classes to compile.
36 */
37public class ClassPathJarEntry extends PathHandler.PathEntry {
38    private final JarFile jarFile;
39
40    public ClassPathJarEntry(Path root) {
41        super(root);
42        if (!Files.exists(root)) {
43            throw new Error(root + " file not found");
44        }
45        try {
46            jarFile = new JarFile(root.toFile());
47        } catch (IOException e) {
48            throw new Error("can not read " + root + " : " + e.getMessage(), e);
49        }
50    }
51
52    @Override
53    protected Stream<String> classes() {
54        return jarFile.stream()
55                      .map(JarEntry::getName)
56                      .filter(Utils::isClassFile)
57                      .map(Utils::fileNameToClassName);
58    }
59
60    @Override
61    protected String description() {
62        return "# jar: " + root;
63    }
64
65    @Override
66    protected byte[] findByteCode(String classname) {
67        try {
68            String filename = Utils.classNameToFileName(classname);
69            JarEntry entry = jarFile.getJarEntry(filename);
70
71            if (entry == null) {
72                return null;
73            }
74
75            try (InputStream is = jarFile.getInputStream(entry)) {
76                return is.readAllBytes();
77            }
78
79        } catch (IOException e) {
80            e.printStackTrace(CompileTheWorld.ERR);
81            return null;
82        }
83    }
84}
85
86