1. /*
  2. * Copyright 2002-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.filters.util;
  18. import java.io.ByteArrayInputStream;
  19. import java.io.IOException;
  20. import org.apache.bcel.classfile.ClassParser;
  21. import org.apache.bcel.classfile.ConstantValue;
  22. import org.apache.bcel.classfile.Field;
  23. import org.apache.bcel.classfile.JavaClass;
  24. /**
  25. * Helper class that filters constants from a Java Class
  26. *
  27. */
  28. public final class JavaClassHelper {
  29. /** System specific line separator. */
  30. private static final String LS = System.getProperty("line.separator");
  31. /**
  32. * Get the constants declared in a file as name=value
  33. *
  34. * @param bytes the class as a array of bytes
  35. * @return a StringBuffer contains the name=value pairs
  36. * @exception IOException if an error occurs
  37. */
  38. public static final StringBuffer getConstants(byte[] bytes)
  39. throws IOException {
  40. final StringBuffer sb = new StringBuffer();
  41. final ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
  42. final ClassParser parser = new ClassParser(bis, "");
  43. final JavaClass javaClass = parser.parse();
  44. final Field[] fields = javaClass.getFields();
  45. for (int i = 0; i < fields.length; i++) {
  46. final Field field = fields[i];
  47. if (field != null) {
  48. final ConstantValue cv = field.getConstantValue();
  49. if (cv != null) {
  50. String cvs = cv.toString();
  51. //Remove start and end quotes if field is a String
  52. if (cvs.startsWith("\"") && cvs.endsWith("\"")) {
  53. cvs = cvs.substring(1, cvs.length() - 1);
  54. }
  55. sb.append(field.getName());
  56. sb.append('=');
  57. sb.append(cvs);
  58. sb.append(LS);
  59. }
  60. }
  61. }
  62. return sb;
  63. }
  64. }