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