1. /*
  2. * Copyright 2000-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. package org.apache.tools.ant.taskdefs.optional.depend;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.util.zip.ZipEntry;
  21. import java.util.zip.ZipInputStream;
  22. /**
  23. * A class file iterator which iterates through the contents of a Java jar
  24. * file.
  25. *
  26. */
  27. public class JarFileIterator implements ClassFileIterator {
  28. /** The jar stream from the jar file being iterated over*/
  29. private ZipInputStream jarStream;
  30. /**
  31. * Construct an iterator over a jar stream
  32. *
  33. * @param stream the basic input stream from which the Jar is received
  34. * @exception IOException if the jar stream cannot be created
  35. */
  36. public JarFileIterator(InputStream stream) throws IOException {
  37. super();
  38. jarStream = new ZipInputStream(stream);
  39. }
  40. /**
  41. * Get the next ClassFile object from the jar
  42. *
  43. * @return a ClassFile object describing the class from the jar
  44. */
  45. public ClassFile getNextClassFile() {
  46. ZipEntry jarEntry;
  47. ClassFile nextElement = null;
  48. try {
  49. jarEntry = jarStream.getNextEntry();
  50. while (nextElement == null && jarEntry != null) {
  51. String entryName = jarEntry.getName();
  52. if (!jarEntry.isDirectory() && entryName.endsWith(".class")) {
  53. // create a data input stream from the jar input stream
  54. ClassFile javaClass = new ClassFile();
  55. javaClass.read(jarStream);
  56. nextElement = javaClass;
  57. } else {
  58. jarEntry = jarStream.getNextEntry();
  59. }
  60. }
  61. } catch (IOException e) {
  62. String message = e.getMessage();
  63. String text = e.getClass().getName();
  64. if (message != null) {
  65. text += ": " + message;
  66. }
  67. throw new RuntimeException("Problem reading JAR file: " + text);
  68. }
  69. return nextElement;
  70. }
  71. }